window.INSTINCTOR_BUILD_TIER = 'free';

(function _impulseDemoMode() {
    try {
        var qs = (window.location && window.location.search) || '';
        if (qs.indexOf('demo=1') < 0) return;
        var STYLE_ID = '__impulse_demo_mode__';
        var CSS_TOP = ''

            + 'iframe#impulse-iframe { cursor: none; }';

        
        
        var CSS_IFR = ''
            + 'body { cursor: none !important; }'
            + '* { cursor: none !important; }'
            + '.impulse-el-toolbar, .impulse-dropzone, .impulse-add-element,'
            + ' .impulse-add-section, .impulse-empty-section, .impulse-element-label,'
            + ' .impulse-empty-page, .impulse-empty-hint, .impulse-empty-placeholder,'
            + ' .impulse-cell-empty-indicator, .impulse-section-name-tag,'
            + ' .impulse-screen-name-tag, .impulse-screen-handle,'
            + ' .impulse-el-resize-handle, .impulse-toolbar { display: none !important; }'
            + '.impulse-el { outline: none !important; box-shadow: none !important; }'
            + '.impulse-el:hover, .impulse-el.selected, .impulse-el:focus,'
            + ' .impulse-el:focus-within, .impulse-el:focus-visible {'
            + ' outline: none !important; box-shadow: none !important; }'
            + '.impulse-el::before, .impulse-el::after { display: none !important; }'
            + '.impulse-rows-cell, .impulse-grid-cell, .impulse-layout-cell {'
            + ' outline: none !important; }';
        function _injectInto(doc, id, css) {
            if (!doc) return;
            if (doc.getElementById(id)) return;
            var s = doc.createElement('style');
            s.id = id;
            s.textContent = css;
            (doc.head || doc.documentElement).appendChild(s);
        }
        
        function _injectTop() { _injectInto(document, STYLE_ID, CSS_TOP); }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', _injectTop);
        } else {
            _injectTop();
        }

        
        function _wireIframe() {
            var ifr = document.getElementById('impulse-iframe');
            if (!ifr) { setTimeout(_wireIframe, 200); return; }
            function _injectIframe() {
                try {
                    var d = ifr.contentDocument;
                    if (!d || !d.body) { setTimeout(_injectIframe, 100); return; }
                    _injectInto(d, STYLE_ID, CSS_IFR);
                } catch (_e) {}
            }
            
            _injectIframe();
            ifr.addEventListener('load', function() {

                
                setTimeout(_injectIframe, 50);
                setTimeout(_injectIframe, 400);
            });
        }
        _wireIframe();
    } catch (_e) {}
})();

window.INSTINCTOR_FREE = {

    
    
    sectionAnims:     ['caustics','rings','concentric'],
    sectionMotion:    ['float','prism','ripple'],
    headlineAnims:    ['', 'build_slots','dof_rack','3d_zoom_out','neon_ignite'],

    
    
    kineticCompositions: ['block-slam','spotlight','wave-build']
};

window.isProLocked = function() { return window.INSTINCTOR_BUILD_TIER === 'free'; };

jQuery(function ($) {
    var $banner = $('#impulse-free-banner');
    if (!$banner.length) return;
    var KEY = 'instinctor_free_banner_dismissed', MONTH = 30 * 864e5;
    try {
        var ts = parseInt(localStorage.getItem(KEY) || '0', 10);
        if (ts && (Date.now() - ts) < MONTH) { $banner.hide(); }
    } catch (e) {}
    $('#impulse-free-banner-dismiss').on('click', function () {
        $banner.hide();
        try { localStorage.setItem(KEY, String(Date.now())); } catch (e) {}
    });
});

document.addEventListener('DOMContentLoaded', function () {
    if (!window.isProLocked || !window.isProLocked()) return;
    var sel = document.getElementById('settings-store-type');
    if (!sel) return;
    var selectedLocked = false;
    sel.querySelectorAll('option[data-pro-type]').forEach(function (o) {
        if (o.selected) selectedLocked = true;
        o.disabled = true;
        if (o.textContent.indexOf('(Pro)') === -1) o.textContent += '  (Pro)';
    });

    
    if (selectedLocked) sel.value = '';
});

document.addEventListener('DOMContentLoaded', function () {
    var ob = document.getElementById('instinctor-onboarding');
    if (!ob) return;
    var go = document.getElementById('instinctor-onboarding-go');
    go.addEventListener('click', function () {
        go.disabled = true;
        var nonce = ob.getAttribute('data-nonce');
        ob.remove();
        var body = new URLSearchParams();
        body.set('action', 'instinctor_complete_onboarding');
        body.set('nonce', nonce);
        fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: body.toString()
        });
        if (typeof window.switchWorkspace === 'function') window.switchWorkspace('settings');
    });
});

window.isProEffect = function(category, key) {
    if (!window.isProLocked()) return false;
    var free = window.INSTINCTOR_FREE[category];
    return free && free.indexOf(key) === -1;
};

window.showProUpgradePrompt = function(featureLabel) {
    if (window._instProUpgradeModalOpen) return;
    window._instProUpgradeModalOpen = true;
    var overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.75);z-index:99999;display:flex;align-items:center;justify-content:center';
    overlay.innerHTML =
        '<div style="background:#1a1d21;border:1px solid #3a3f44;border-radius:6px;padding:32px;max-width:420px;text-align:center;color:#e0e0e0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif">' +
        '<div style="font-size:13px;color:#999;margin-bottom:8px">' + (featureLabel || 'This feature') + '</div>' +
        '<div style="font-size:18px;font-weight:600;margin-bottom:6px">Available in Instinctor Pro</div>' +
        '<div style="font-size:12px;color:#999;line-height:1.6;margin-bottom:20px">40+ environments, 33 motion presets, full 3D text engine, SMS &amp; WhatsApp notifications, unlimited animation layers.</div>' +
        '<a href="https://instinctor.com/pro" target="_blank" rel="noopener" style="display:inline-block;background:#fff;color:#1d2327;padding:9px 20px;border-radius:3px;font-size:12px;font-weight:600;text-decoration:none;margin-right:6px">Get Instinctor Pro</a>' +
        '<button type="button" id="impulse-pro-modal-close" style="background:transparent;border:1px solid #3a3f44;color:#999;padding:8px 16px;border-radius:3px;font-size:12px;cursor:pointer">Close</button>' +
        '</div>';
    document.body.appendChild(overlay);
    var close = function() {
        if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
        window._instProUpgradeModalOpen = false;
    };
    overlay.addEventListener('click', function(e) { if (e.target === overlay) close(); });
    overlay.querySelector('#impulse-pro-modal-close').addEventListener('click', close);
};

document.addEventListener('click', function(e) {
    var t = e.target;
    while (t && t !== document) {
        if (t.getAttribute && t.getAttribute('data-pro-locked') === '1') {
            e.preventDefault();
            e.stopPropagation();
            window.showProUpgradePrompt(t.getAttribute('data-pro-label') || '');
            return;
        }
        t = t.parentNode;
    }
}, true);

var ImpC = {
    bg:       '#111316',
    surface:  '#1a1d21',
    surface2: '#1d2327',
    panel:    '#2a2e33',
    border:   '#3a3f44',
    dim:      '#555',
    muted:    '#999',
    text:     '#e0e0e0',
    light:    '#f5f5f5',
    white:    '#fff',
};

var OVFX_PRESETS = [
    { v: 'noise',    l: 'Noise' },
    { v: 'ripple',   l: 'Ripple' },
    { v: 'liquid',   l: 'Liquid' },
    { v: 'shatter',  l: 'Shatter' },
    { v: 'static',   l: 'Static' },
    { v: 'melt',     l: 'Melt' },
    { v: 'focus',    l: 'Focus' },
    { v: 'tumble',   l: 'Tumble' },
    { v: 'tunnel',   l: 'Tunnel' },
    { v: 'wave',     l: 'Wave' },
    { v: 'bars',     l: 'Bars' },
    { v: 'cards',    l: 'Cards' },
    { v: 'pop',      l: 'Pop' },
    { v: 'fly',      l: 'Fly' },
    { v: 'rise',     l: 'Rise' },
    { v: 'converge', l: 'Converge' }
];
var OVFX_FLAT = [];
var OVFX_SLIDERS = {
    noise:    [['ovfx_p1','Intensity',65,0,100,''], ['ovfx_p2','Grain',45,0,100,''],     ['ovfx_p3','Depth',40,0,100,'']],
    ripple:   [['ovfx_p1','Intensity',55,0,100,''], ['ovfx_p2','Waves',40,0,100,''],     ['ovfx_p3','Depth',40,0,100,'']],
    liquid:   [['ovfx_p1','Intensity',65,0,100,''], ['ovfx_p2','Flow',45,0,100,''],      ['ovfx_p3','Depth',35,0,100,'']],
    shatter:  [['ovfx_p1','Intensity',70,0,100,''], ['ovfx_p2','Grain',60,0,100,''],     ['ovfx_p3','Depth',45,0,100,'']],
    static:   [['ovfx_p1','Intensity',55,0,100,''], ['ovfx_p2','Grain',80,0,100,''],     ['ovfx_p3','Depth',30,0,100,'']],
    melt:     [['ovfx_p1','Intensity',60,0,100,''], ['ovfx_p2','Grain',40,0,100,''],     ['ovfx_p3','Depth',35,0,100,'']],
    focus:    [['ovfx_p1','Blur',70,0,100,''],      ['ovfx_p2','Grain',35,0,100,''],     ['ovfx_p3','Depth',40,0,100,'']],
    tumble:   [['ovfx_p1','Angle',55,0,100,''],     ['ovfx_p2','Depth',50,0,100,''],     ['ovfx_p3','Spin',30,0,100,'']],
    tunnel:   [['ovfx_p1','Depth',70,0,100,''],     ['ovfx_p2','Blur',35,0,100,''],      ['ovfx_p3','Spin',25,0,100,'']],
    wave:     [['ovfx_p1','Amplitude',55,0,100,''], ['ovfx_p2','Frequency',40,0,100,''], ['ovfx_p3','Stagger',55,0,100,'']],
    bars:     [['ovfx_p1','Depth',60,0,100,''],     ['ovfx_p2','Spread',50,0,100,''],    ['ovfx_p3','Stagger',55,0,100,'']],
    cards:    [['ovfx_p1','Depth',45,0,100,''],     ['ovfx_p2','Flip',65,0,100,''],      ['ovfx_p3','Stagger',55,0,100,'']],
    pop:      [['ovfx_p1','Scale',60,0,100,''],     ['ovfx_p2','Depth',45,0,100,''],     ['ovfx_p3','Stagger',55,0,100,'']],
    fly:      [['ovfx_p1','Distance',55,0,100,''],  ['ovfx_p2','Depth',50,0,100,''],     ['ovfx_p3','Stagger',55,0,100,'']],
    rise:     [['ovfx_p1','Lift',50,0,100,''],      ['ovfx_p2','Depth',45,0,100,''],     ['ovfx_p3','Stagger',55,0,100,'']],
    converge: [['ovfx_p1','Spread',55,0,100,''],    ['ovfx_p2','Spin',50,0,100,''],      ['ovfx_p3','Stagger',55,0,100,'']]
};
function ovfxSliderRow(key, label, val, min, max, unit) {
    return '<div class="impulse-setting-row inline-slider"><label>' + label + '</label>'
        + '<span class="impulse-slider-value">' + val + unit + '</span>'
        + '<div class="impulse-slider-row" data-unit="' + unit + '">'
        + '<input type="range" name="' + key + '" value="' + val + '" min="' + min + '" max="' + max + '" step="1">'
        + '</div></div>';
}
function buildOvfxSliders(preset, settings) {
    
    var rows = (OVFX_SLIDERS[preset] || OVFX_SLIDERS.noise)
        .concat([['ovfx_speed', 'Speed', 5, 1, 10, '']]);
    var h = '';
    for (var i = 0; i < rows.length; i++) {
        var r = rows[i];
        var saved = (settings && settings[r[0]] !== undefined && settings[r[0]] !== '')
            ? settings[r[0]] : r[2];
        h += ovfxSliderRow(r[0], r[1], saved, r[3], r[4], r[5]);
    }
    return h;
}

function applyOvfxLivePreview() {
    try {
        var id  = $('.impulse-panel-right').data('element-id');
        var ifr = document.getElementById('impulse-iframe');
        var doc = ifr && (ifr.contentDocument || (ifr.contentWindow && ifr.contentWindow.document));
        if (!doc || !id) return;
        var sec = doc.querySelector('.impulse-el[data-id="' + id + '"] > section.impulse-section')
               || doc.querySelector('.impulse-el[data-id="' + id + '"] section.impulse-section')
               || doc.querySelector('.impulse-el[data-id="' + id + '"] section');
        if (!sec) return;
        var fx  = ($('input[name="ovfx"]').val() || '').trim();
        var car = sec.querySelector(':scope > .impulse-overlay-fx');
        if (!fx) {
            if (car && car.parentNode) car.parentNode.removeChild(car);
        } else {
            if (!car) {
                car = doc.createElement('div');
                car.className = 'impulse-overlay-fx';
                car.setAttribute('aria-hidden', 'true');
                car.style.display = 'none';
                sec.appendChild(car);
            }
            var num = function(n, d) { var v = parseFloat($('input[name="' + n + '"]').val()); return isNaN(v) ? d : v; };
            car.setAttribute('data-ovfx', JSON.stringify({
                fx:    fx,
                ease:  ($('input[name="ovfx_ease"]').val() || 'spring'),
                speed: num('ovfx_speed', 5),
                p1:    num('ovfx_p1', 50),
                p2:    num('ovfx_p2', 50),
                p3:    num('ovfx_p3', 50),
                c1:    ($('input[name="ovfx_c1"]').val() || ''),
                c2:    ($('input[name="ovfx_c2"]').val() || ''),
                editor: true
            }));
        }
        var win = ifr.contentWindow;
        
        if (win && win.ImpulseOverlayFX && win.ImpulseOverlayFX.play) win.ImpulseOverlayFX.play(sec);
    } catch (e) {}
}

window.instinctorAdminEmail = window.Impulse.adminEmail;

window._emailTemplateStates = window.Impulse.emailTemplateStates;

if (typeof ajaxurl === 'undefined') {
    var ajaxurl = window.Impulse.ajaxUrl;
}

function _doUpgradeCheckout(hosting) {
    window.showToast('Opening checkout\u2026', 'info');
    $.post(window.Impulse.ajaxUrl, {
        action:     'instinctor_proxy_checkout',
        nonce:      window.Impulse.adminNonce,
        tier:       'pro',
        billing:    'monthly',
        hosting:    hosting ? 1 : 0,
        return_url: window.location.href
    }, function(resp) {
        if (resp && resp.success && resp.data && resp.data.checkout_url) {
            if (resp.data.license_key) {
                $.post(window.Impulse.ajaxUrl, {
                    action: 'instinctor_store_pending_license',
                    nonce:  window.Impulse.adminNonce,
                    key:    resp.data.license_key
                });
            }
            window.location.href = resp.data.checkout_url;
        } else {
            var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Checkout unavailable.';
            window.showToast(msg, 'error');
        }
    }).fail(function() {
        window.showToast('Connection error. Please try again.', 'error');
    });
}

window.triggerUpgradeCheckout = function() {
    jQuery('#impulse-upgrade-modal').remove();
    var PRO = 29.90, HOST = 14.90;
    var fmt = function(n) { return '$' + n.toFixed(2) + '/mo'; };
    var $ov = jQuery(
        '<div id="impulse-upgrade-modal" style="position:fixed;inset:0;z-index:2147483600;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;">' +
          '<div style="background:#fff;width:360px;max-width:92vw;border-radius:6px;padding:24px;box-shadow:0 12px 40px rgba(0,0,0,0.3);color:#1d2327;">' +
            '<div style="font-size:16px;font-weight:600;margin-bottom:4px;">Upgrade to Pro</div>' +
            '<div style="font-size:12px;color:#999;margin-bottom:18px;">Everything in Instinctor, unlocked.</div>' +
            '<div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:14px;">' +
              '<span>Instinctor Pro</span><span>' + fmt(PRO) + '</span></div>' +
            '<label style="display:flex;align-items:flex-start;gap:10px;cursor:pointer;padding:12px;border:1px solid #e0e0e0;border-radius:5px;margin-bottom:16px;">' +
              '<input type="checkbox" id="impulse-upgrade-hosting" style="margin-top:2px;accent-color:#1d2327;">' +
              '<span style="flex:1;">' +
                '<span style="display:flex;justify-content:space-between;font-size:13px;"><span>Host it for me</span><span>+' + fmt(HOST) + '</span></span>' +
                '<span style="display:block;font-size:11px;color:#999;margin-top:3px;line-height:1.4;">We run your site on our servers. You keep your own domain.</span>' +
              '</span></label>' +
            '<div style="display:flex;justify-content:space-between;font-size:14px;font-weight:600;border-top:1px solid #e0e0e0;padding-top:12px;margin-bottom:18px;">' +
              '<span>Total</span><span id="impulse-upgrade-total">' + fmt(PRO) + '</span></div>' +
            '<button id="impulse-upgrade-go" style="width:100%;height:38px;background:#1d2327;color:#fff;border:none;border-radius:5px;font-size:13px;font-weight:600;cursor:pointer;transition:background 0.18s ease-in-out;">Continue to checkout</button>' +
            '<button class="impulse-upgrade-cancel" style="width:100%;height:32px;background:none;color:#999;border:none;font-size:12px;cursor:pointer;margin-top:8px;">Cancel</button>' +
          '</div>' +
        '</div>'
    );
    jQuery('body').append($ov);
    $ov.on('change', '#impulse-upgrade-hosting', function() {
        var on = $ov.find('#impulse-upgrade-hosting').is(':checked');
        $ov.find('#impulse-upgrade-total').text(fmt(PRO + (on ? HOST : 0)));
    });
    $ov.on('click', '.impulse-upgrade-cancel', function() { $ov.remove(); });
    $ov.on('click', function(e) { if (e.target === $ov[0]) $ov.remove(); });
    $ov.on('click', '#impulse-upgrade-go', function() {
        var hosting = $ov.find('#impulse-upgrade-hosting').is(':checked') ? 1 : 0;
        $ov.remove();
        _doUpgradeCheckout(hosting);
    });
};

jQuery(function($) {
    $(document).on('click', '.impulse-upgrade-link', function(e) {
        e.preventDefault();
        if (window.triggerUpgradeCheckout) window.triggerUpgradeCheckout();
    });
});

window.RESPONSIVE_SETTINGS = [
    
    'width', 'height', 'max_width', 'min_width', 'max_height', 'min_height',
    'form_width', 'button_width', 'image_width', 'image_height', 'icon_size', 'section_max_width',
    'logo_height', 'avatar_size', 'card_width', 'card_height', 'card_max_width', 'card_radius',
    'button_size', 'image_size', 'min_card_width', 'bundle_width',
    'focal_point', 

    'padding', 'padding_top', 'padding_right', 'padding_bottom', 'padding_left',
    'padding_x', 'padding_y', 'inner_padding', 'padding_sides', 'side_padding',
    'box_padding', 'content_padding', 'button_padding',

    'split_ratio', 'peek_offset', 'blur_intensity',
    
    'acc_width', 'tiles_cols',

    'margin', 'margin_top', 'margin_right', 'margin_bottom', 'margin_left',

    'size', 'font_size', 'line_height', 'letter_spacing',
    'title_size', 'subtitle_size', 'description_size', 'price_size',
    'heading_size', 'text_size', 'label_size', 'button_font_size',
    'content_size', 'front_title_size', 'front_content_size', 'back_title_size', 'back_content_size',
    'menu_font_size', 'element_text_size', 'element_icon_size',

    'columns', 'cols', 'rows', 'column_count', 'grid_columns', 'items_per_row', 'items_to_show',
    'gap', 'row_gap', 'column_gap', 'col_gap', 'spacing', 'item_gap', 'cell_gap',
    'gap_horizontal', 'gap_vertical', 'menu_gap', 'element_spacing', 'text_spacing',
    'flex_direction', 'direction',
    'align', 'alignment', 'text_align', 'content_align', 'items_align', 'box_align',
    'justify', 'justify_content',
    'vertical_align',
    'visibility',

    'border_radius', 'radius', 'cell_radius', 'border_width', 'field_border_width',
    'icon_radius', 'icon_border_width', 'button_radius', 'field_radius',
    
    'border_color', 'border_gradient_to', 'border_gradient_angle', 'border_mouse_sens', 'border_spin_speed',

    'section_padding', 'content_width', 'container_width',
    'min_height_value', 'row_height',

    'slides_to_show', 'slide_gap', 'autoplay_speed', 'transition_speed',
    'slide_effect', 'slider_effect',

    'products_per_row',

    'field_gap',

    'icon_padding', 'icon_spacing',

    

    

    
    'thickness', 'height_px', 'position_align', 'tilt',

    'animation_duration', 'animation_delay', 'hover_transition', 'hover_shadow_size',
    'overlay_opacity', 'zoom', 'zoom_scale',

    

    
    
    'bg_animation_enabled',

    'shadow_h', 'shadow_v', 'shadow_blur',

    'offset_x', 'offset_y', 'sticky_offset', 'sticky_z_index',

    'fit_min', 'fit_max',

    'line_1_size',

    
    
    'line_1', 'content',

    'value', 'scroll_percent', 'show_after',

    'sticky', 'announcement_enabled', 'show_site_name', 'show_border', 'show_cart', 'show_account', 'show_shadow', 'show_cta',

    
    
    'btn_height', 'btn_size', 'weight',

    'la_font_size', 'la_image_width', 'la_gap_below',

    'cell_padding_h', 'cell_padding_v', 'icon_gap', 'item_space', 'depth_intensity', 'tilt_intensity',

    'popup_width', 'popup_height', 'popup_padding', 'popup_radius',
    'oc_width', 'oc_padding',

    'preview_max_width',

    'pl_title_size', 'pl_desc_size', 'pl_price_size', 'pl_spacing', 'pl_icon_size',

    'checkout_design_button_radius', 'checkout_design_field_border_width', 'checkout_design_field_radius',

    'number_size', 'ah_duration', 'ah_pause', 'duration',

    'scroll_speed', 'trigger_delay', 'trigger_scroll',

    'rotation', 'z_index',
    
    'line_1_depth', 'dof_intensity', 'perspective',

    

    
    'bg_image', 'bg_position', 'bg_size', 'bg_fixed', 'bg_parallax_sens',

    'section_tilt', 'section_tilt_intensity', 'section_ambient', 'section_ambient_intensity', 'section_ambient_hue', 'section_ambient_over_content',

    'aspect_ratio',

    'show_image', 'show_quantity', 'show_subtotal', 'show_header', 'show_table'
];

var LucidePickerCategories = {
    'UI':['search','settings','sliders-horizontal','list-filter','menu','ellipsis','ellipsis-vertical','check','circle-check','x','circle-x','plus','minus','info','circle-alert','triangle-alert','bell','eye','eye-off','lock','lock-open','shield','toggle-left','power','log-in','log-out','copy','clipboard','trash-2','pencil','save','refresh-cw','rotate-cw','thumbs-up','thumbs-down','hand'],
    'Arrows':['arrow-up','arrow-down','arrow-left','arrow-right','arrow-up-right','arrow-down-left','chevron-up','chevron-down','chevron-left','chevron-right','circle-arrow-up','circle-arrow-down','circle-arrow-left','circle-arrow-right','external-link','link','move'],
    'Commerce':['shopping-cart','shopping-bag','store','package','box','truck','warehouse','credit-card','wallet','banknote','coins','circle-dollar-sign','piggy-bank','receipt','tag','percent','badge-percent','gift','award','trophy','crown','gem'],
    'Communication':['mail','mail-open','inbox','send','forward','message-circle','message-square','phone','phone-call','video','mic','headphones','at-sign','paperclip','megaphone','rss'],
    'Content':['file','file-text','folder','folder-open','book','book-open','newspaper','scroll','image','camera','film','type','bold','italic','list','list-ordered','quote','download','upload','share','printer','qr-code'],
    'People':['user','user-plus','user-check','users','circle-user','badge-check','heart','heart-handshake','smile','frown','brain','lightbulb','graduation-cap','house','building','building-2','landmark','briefcase','calendar','clock','timer','alarm-clock'],
    'Tech':['monitor','smartphone','tablet','laptop','tv','cpu','hard-drive','database','server','cloud','wifi','globe','earth','map','map-pin','navigation','compass','code','terminal','git-branch','bot','sparkles','wand-sparkles','zap','atom'],
    'Nature':['sun','moon','cloud-rain','snowflake','wind','thermometer','flame','droplet','leaf','tree-pine','flower','sprout','mountain','sunrise','sunset'],
    'Shapes':['circle','square','triangle','hexagon','octagon','star','sparkle','heart','diamond','bookmark','flag','target','crosshair','circle-dot','circle-plus','circle-minus','square-check','square-x']
};
var LucidePickerSVG = (window.ImpulseLucideAll || {});
function lucideSvg(name, size) {
    var inner = (window.ImpulseLucideAll || LucidePickerSVG || {})[name];
    if (!inner) return '';
    size = size || 24;
    return '<svg viewBox="0 0 24 24" width="' + size + '" height="' + size + '" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' + inner + '</svg>';
}

jQuery(function($) {

    

    

    

    

    

    

    
    $(document).on('input change', '[data-live-target]', function() {
        var $control = $(this);
        var target = $control.data('live-target');
        var value = $control.val();

        if ($control.is(':checkbox')) {
            value = $control.is(':checked') ? ($control.data('live-checked') || 'block') : ($control.data('live-unchecked') || 'none');
        }

        if ($control.is('input[type="color"]') && value && !value.startsWith('#')) {
            value = '#' + value;
        }

        var unit = $control.data('live-unit');
        if (unit && value !== '' && !isNaN(value)) {
            value = value + unit;
        }

        var iframeId = $control.data('live-iframe');
        var $context;
        if (iframeId) {
            var $iframe = $('#' + iframeId);
            if ($iframe.length && $iframe[0].contentDocument) {
                $context = $($iframe[0].contentDocument);
            } else {
                return; 
            }
        } else {
            $context = $(document);
        }
        
        var $targets = $context.find(target);
        if (!$targets.length) return;

        var css = $control.data('live-css');
        var attr = $control.data('live-attr');
        var transform = $control.data('live-transform');
        
        if (css) {
            
            $targets.css(css, value);
        } else if (attr) {
            
            $targets.attr(attr, value);
        } else if ($control.data('live-text') !== undefined) {
            
            $targets.text(value);
        } else if ($control.data('live-html') !== undefined) {
            
            $targets.html(value);
        } else if (transform) {
            
            $targets.css('transform', transform + '(' + value + ')');
        } else if ($control.data('live-style') !== undefined) {
            
            $targets.attr('style', value);
        }

        $(document).trigger('impulse:live-update', {
            control: $control,
            target: target,
            value: value,
            $targets: $targets
        });
    });

    

    

    $(document).on('input', 'input[type="range"]', function() {
        if ($(this).data('schema')) return; 
        var $slider = $(this);
        var $valueDisplay = $slider.closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value');
        if (!$valueDisplay.length) {
            $valueDisplay = $slider.closest('.impulse-slider-row').find('.impulse-slider-value');
        }
        if ($valueDisplay.length) {
            var unit = $slider.closest('[data-unit]').data('unit');
            if (unit === undefined || unit === null) unit = '';
            $valueDisplay.text($slider.val() + unit);
        }
    });

    $(document).on('click', '.impulse-workspace-btn, .impulse-workspace-link', function(e) {
        e.preventDefault();
        var workspace = $(this).data('workspace');
        
        if (workspace) {
            switchWorkspace(workspace);
        }
    });

    
    var thumbnailsLoaded = false;
    function lazyLoadThumbnailIframes() {
        if (thumbnailsLoaded) return;
        thumbnailsLoaded = true;
        
        var $grid = $('#impulse-canvas-grid');
        $grid.css('opacity', '1');
        $('#impulse-grid-loading').hide();
    }

    var isDraggingCard = false;
    $(document).ready(function() {
        var initialWorkspace = window.Impulse.workspace;
        if (initialWorkspace === 'impulse') {
            
            setTimeout(lazyLoadThumbnailIframes, 1000);
        }

        var gridEl = document.getElementById('impulse-canvas-grid');
        if (gridEl && typeof Sortable !== 'undefined') {
            Sortable.create(gridEl, {
                animation: 200,
                delay: 150,
                delayOnTouchOnly: true,
                ghostClass: 'sortable-ghost',
                dragClass: 'sortable-drag',
                filter: '.trashed, .impulse-card-status',
                preventOnFilter: false,
                emptyInsertThreshold: 40,
                swapThreshold: 0.65,
                invertSwap: true,
                onStart: function() { isDraggingCard = true; },
                onEnd: function() {
                    setTimeout(function() { isDraggingCard = false; }, 50);
                    
                    var order = [];
                    $(gridEl).find('.impulse-page-card:not(.trashed)').each(function() {
                        order.push($(this).data('id'));
                    });
                    if (order.length) {
                        $.ajax({
                            url: Impulse.api + 'pages/reorder',
                            method: 'POST',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            contentType: 'application/json',
                            data: JSON.stringify({ order: order })
                        });
                    }
                }
            });
        }

        (function(){
          var grid = document.getElementById('impulse-canvas-grid');
          if(!grid || typeof window.jQuery === 'undefined' || typeof MutationObserver === 'undefined') return;
          var ORDER = ['Marketing','SEO · Verticals','SEO · Guides','SEO · Alternatives','SEO · Comparisons','SEO · Category','Funnel','Legal','Pages'];

          var DEFAULT_COLLAPSED = {'SEO · Verticals':1,'SEO · Guides':1,'SEO · Alternatives':1,'SEO · Comparisons':1,'SEO · Category':1};
          function isCollapsed(g, coll){ return (g in coll) ? !!coll[g] : !!DEFAULT_COLLAPSED[g]; }

          try { if(!localStorage.getItem('impulse_pg_seo_default_v1')){ var _c={}; try{ _c=JSON.parse(localStorage.getItem('impulse_pg_collapsed')||'{}'); }catch(_e){} Object.keys(DEFAULT_COLLAPSED).forEach(function(g){ delete _c[g]; }); localStorage.setItem('impulse_pg_collapsed', JSON.stringify(_c)); localStorage.setItem('impulse_pg_seo_default_v1','1'); } } catch(_e){}
          function grp(slug, type){
            if(type === 'post') return null; slug = String(slug || '');
            if(/-website$/.test(slug)) return 'SEO · Verticals';
            if(/-alternative$/.test(slug)) return 'SEO · Alternatives';
            if(/-vs-/.test(slug)) return 'SEO · Comparisons';
            if(/^how-to-/.test(slug)) return 'SEO · Guides';
            if(/^(why-|do-i-|is-a-|is-it-|cheapest-|how-much-|how-do-)/.test(slug)) return 'SEO · Guides';
            if(/-software$/.test(slug) || /^website-builder-for-/.test(slug) || /-for-/.test(slug)) return 'SEO · Category';
            if(['cart','checkout','order-received'].indexOf(slug) >= 0) return 'Funnel';
            if(['terms','privacy'].indexOf(slug) >= 0) return 'Legal';
            if(['instinctor','solutions','instudio','pizza','restaurant','apply','home'].indexOf(slug) >= 0) return 'Marketing';
            return 'Pages';
          }
          var obs = null, t = null;
          function regroup(){
            if(typeof isDraggingCard !== 'undefined' && isDraggingCard){ t = setTimeout(regroup, 160); return; }
            if(obs) obs.disconnect();
            var $g = jQuery(grid);
            $g.find('.impulse-pg-group').remove();
            var cards = $g.find('.impulse-page-card').not('.trashed').toArray();
            if(cards.length < 8){ if(obs) obs.observe(grid, {childList:true}); return; }
            var groups = {};
            cards.forEach(function(c){ var $c = jQuery(c); var g = grp($c.attr('data-slug'), $c.attr('data-type')); if(g === null) return; (groups[g] = groups[g] || []).push(c); });
            var coll = {}; try{ coll = JSON.parse(localStorage.getItem('impulse_pg_collapsed') || '{}'); }catch(e){}
            ORDER.forEach(function(g){
              var list = groups[g]; if(!list || !list.length) return;
              var c0 = isCollapsed(g, coll);
              var h = document.createElement('div');
              h.className = 'impulse-pg-group' + (c0 ? ' is-collapsed' : '');
              h.setAttribute('data-group', g);
              h.innerHTML = '<span class="impulse-pg-caret">' + (c0 ? '›' : '⌄') + '</span><span class="impulse-pg-name"></span><span class="impulse-pg-count"></span>';
              h.querySelector('.impulse-pg-name').textContent = g;
              h.querySelector('.impulse-pg-count').textContent = list.length;
              grid.appendChild(h);
              list.forEach(function(c){ c.style.display = c0 ? 'none' : ''; grid.appendChild(c); });
            });
            $g.find('.impulse-page-card.trashed').each(function(){ grid.appendChild(this); });
            if(obs) obs.observe(grid, {childList:true});
          }
          obs = new MutationObserver(function(){ clearTimeout(t); t = setTimeout(regroup, 120); });
          jQuery(document).on('click', '.impulse-pg-group', function(){
            var g = jQuery(this).attr('data-group');
            var coll = {}; try{ coll = JSON.parse(localStorage.getItem('impulse_pg_collapsed') || '{}'); }catch(e){}
            coll[g] = !isCollapsed(g, coll); localStorage.setItem('impulse_pg_collapsed', JSON.stringify(coll)); regroup();
          });
          regroup();
        })();
    });

    function positionWorkspaceTrack() {
        var $nav   = $('#impulse-workspace-nav');
        var $track = $('#impulse-workspace-track');
        var $active = $nav.find('.impulse-workspace-btn.active');
        if (!$active.length || !$track.length) return;
        var navLeft   = $nav.offset().left + parseInt($nav.css('padding-left'), 10);
        var btnLeft   = $active.offset().left;
        var btnWidth  = $active.outerWidth();
        $track.css({ width: btnWidth + 'px', transform: 'translateX(' + (btnLeft - navLeft) + 'px)' })
              .addClass('positioned');
    }
    window.positionWorkspaceTrack = positionWorkspaceTrack;

    function switchWorkspace(workspace) {
        
        $('.impulse-editor').attr('data-workspace', workspace);

        $('.impulse-workspace-btn, .impulse-workspace-link').removeClass('active');
        $('.impulse-workspace-btn[data-workspace="' + workspace + '"], .impulse-workspace-link[data-workspace="' + workspace + '"]').addClass('active');
        positionWorkspaceTrack();

        $('.impulse-workspace').hide();
        
        var showWs = (workspace === 'settings') ? 'store' : workspace;
        $('.impulse-workspace[data-workspace="' + showWs + '"]').show();

        var url = new URL(window.location.href);
        if (workspace === 'impulse') {
            url.searchParams.delete('workspace');
        } else {
            url.searchParams.set('workspace', workspace);
        }
        window.history.pushState({ workspace: workspace }, '', url.toString());

        localStorage.setItem('impulse-workspace', workspace);

        if (workspace === 'impulse') {
            $('.impulse-only').show();
            $('.impulse-editing-only').show();
            
            $('.impulse-brand-name').toggle(!Impulse.pageId);
        } else {
            $('.impulse-only').hide();
            $('.impulse-editing-only').hide();
            
            $('.impulse-brand-name').show();
        }

        if (workspace === 'chat') {
            $('#impulse-chat-save-status').show();
            $('#impulse-chat-toggle').show();
            $('.impulse-topbar-builder-controls').addClass('impulse-hidden');
            $('#impulse-preview').hide();
            $('#impulse-store-settings-btn').hide();
            $('#topbar-add-product').hide();
            $('#topbar-add-service').hide();
            $('#topbar-add-booking').hide();
        } else if (workspace === 'impulse') {
            $('#impulse-chat-save-status').hide();
            $('#impulse-chat-toggle').hide();
            $('.impulse-topbar-builder-controls').removeClass('impulse-hidden');
            $('#impulse-preview').show();
            $('#impulse-store-settings-btn').hide();
            $('#topbar-add-product').hide();
            $('#topbar-add-service').hide();
            $('#topbar-add-booking').hide();

            lazyLoadThumbnailIframes();

            

            if (window._impulseProductsDirty && Impulse.pageId) {
                window._impulseProductsDirty = false;
                _refreshProductBlocks();
            }
        } else if (workspace === 'store') {
            $('#impulse-chat-save-status').hide();
            $('#impulse-chat-toggle').hide();
            $('.impulse-topbar-builder-controls').addClass('impulse-hidden');
            $('#impulse-preview').hide();
            $('#impulse-store-settings-btn').show();
            
            $('#topbar-add-product').toggle(typeof currentSection !== 'undefined' && currentSection === 'products');
            
            $('#impulse-store-nav').show();
            $('.impulse-store-grid').removeClass('settings-active');
            
            var _restoreSection = (typeof currentSection !== 'undefined' && currentSection !== 'settings') ? currentSection : 'orders';
            if (typeof switchStoreSection === 'function') switchStoreSection(_restoreSection);
        } else if (workspace === 'settings') {
            $('#impulse-chat-save-status').hide();
            $('#impulse-chat-toggle').hide();
            $('.impulse-topbar-builder-controls').addClass('impulse-hidden');
            $('#impulse-preview').hide();
            $('#impulse-store-settings-btn').hide();
            $('#topbar-add-product').hide();
            $('#topbar-add-service').hide();
            $('#topbar-add-booking').hide();
        } else if (workspace === 'seo') {
            $('#impulse-chat-save-status').hide();
            $('#impulse-chat-toggle').hide();
            $('.impulse-topbar-builder-controls').addClass('impulse-hidden');
            $('#impulse-preview').hide();
            $('#impulse-store-settings-btn').hide();
            $('#topbar-add-product').hide();
            $('#topbar-add-service').hide();
            $('#topbar-add-booking').hide();
        } else {
            
            $('#impulse-chat-save-status').hide();
            $('#impulse-chat-toggle').hide();
            $('.impulse-topbar-builder-controls').addClass('impulse-hidden');
            $('#impulse-preview').hide();
            $('#impulse-store-settings-btn').hide();
            $('#topbar-add-service').hide();
            $('#topbar-add-booking').hide();
        }

        $(document).trigger('impulse:workspace:' + workspace);
    }

    
    function _refreshProductBlocks() {
        var iframe = document.getElementById('impulse-iframe');
        var doc = iframe && (iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document));
        if (!doc) return;
        doc.querySelectorAll('.impulse-el[data-type="products"]').forEach(function(el) {
            var pid = parseInt(el.getAttribute('data-id'), 10);
            if (pid && typeof refreshElement === 'function') refreshElement(pid);
        });
    }

    
    
    $(document).ajaxSuccess(function(event, xhr, settings) {
        var u = (settings && settings.url) || '';
        var m = ((settings && settings.type) || '').toUpperCase();
        if (/\/products?\b/i.test(u) && (m === 'POST' || m === 'PUT' || m === 'PATCH' || m === 'DELETE')) {
            window._impulseProductsDirty = true;
        }
    });

    $(window).on('popstate', function(e) {
        if (e.originalEvent.state && e.originalEvent.state.workspace) {
            switchWorkspace(e.originalEvent.state.workspace);
        }
    });

    
    
    (function() {
        var url = new URL(window.location.href);
        var urlWorkspace = url.searchParams.get('workspace');
        var savedWorkspace = localStorage.getItem('impulse-workspace');
        if (!urlWorkspace && savedWorkspace) {
            var validWorkspaces = ['impulse', 'chat', 'store', 'seo', 'settings'];
            if (validWorkspaces.indexOf(savedWorkspace) !== -1) {
                switchWorkspace(savedWorkspace);
            }
        }
    })();

    
    
    (function() {
        var $nav = $('#impulse-workspace-nav');
        var dragSrcBtn = null;

        function savePrefs(data) {
            data.action = 'instinctor_save_workspace_prefs';
            data.nonce = Impulse.adminNonce;
            $.post(Impulse.products.ajaxurl, data);
        }

        function getOrder() {
            return $nav.find('.impulse-workspace-btn').map(function() {
                return $(this).data('workspace');
            }).get();
        }

        $nav.on('dragstart', '.impulse-workspace-btn', function(e) {
            dragSrcBtn = this;
            $(this).addClass('dragging');
            $nav.addClass('drag-active');
            e.originalEvent.dataTransfer.effectAllowed = 'move';
            e.originalEvent.dataTransfer.setData('text/plain', $(this).data('workspace'));
        });
        
        $nav.on('dragover', '.impulse-workspace-btn', function(e) {
            if (!dragSrcBtn || this === dragSrcBtn) return;
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'move';

            var rect = this.getBoundingClientRect();
            var midX = rect.left + rect.width / 2;
            $(this).removeClass('drag-over-left drag-over-right');
            if (e.originalEvent.clientX < midX) {
                $(this).addClass('drag-over-left');
            } else {
                $(this).addClass('drag-over-right');
            }
        });
        
        $nav.on('dragleave', '.impulse-workspace-btn', function() {
            $(this).removeClass('drag-over-left drag-over-right');
        });
        
        $nav.on('drop', '.impulse-workspace-btn', function(e) {
            e.preventDefault();
            if (!dragSrcBtn || this === dragSrcBtn) return;
            
            var $target = $(this);
            var $src = $(dragSrcBtn);
            $target.removeClass('drag-over-left drag-over-right');

            var rect = this.getBoundingClientRect();
            var midX = rect.left + rect.width / 2;
            
            if (e.originalEvent.clientX < midX) {
                $src.insertBefore($target);
            } else {
                $src.insertAfter($target);
            }

            savePrefs({ order: getOrder() });
        });
        
        $nav.on('dragend', '.impulse-workspace-btn', function() {
            $(this).removeClass('dragging');
            $nav.removeClass('drag-active');
            $nav.find('.impulse-workspace-btn').removeClass('drag-over-left drag-over-right');
            dragSrcBtn = null;
        });

        $(document).on('dragend.workspacenav', function() {
            $nav.find('.impulse-workspace-btn').removeClass('drag-over-left drag-over-right dragging');
            $nav.removeClass('drag-active');
            dragSrcBtn = null;
        });
    })();

    
    
    (function() {
        function saveTabPref(data) {
            data.action = 'instinctor_save_workspace_prefs';
            data.nonce = Impulse.adminNonce;
            $.post(Impulse.products.ajaxurl, data);
        }

        function showTabToast(label) {
            var $toast = $('#impulse-workspace-toast');
            if (!$toast.length) return;
            $toast.text(label).addClass('visible');
            clearTimeout(window._tabToastTimer);
            window._tabToastTimer = setTimeout(function() { $toast.removeClass('visible'); }, 1800);
        }

        (function() {
            var timer = null, fired = false;
            $(document).on('mousedown', '.impulse-store-nav-btn', function(e) {
                if (e.button !== 0) return;
                var $btn = $(this);
                var section = $btn.data('store-section');
                fired = false;
                timer = setTimeout(function() {
                    fired = true;
                    var cur = Impulse.storeSectionDefault || '';
                    var next = (cur === section) ? '' : section;
                    Impulse.storeSectionDefault = next;
                    $('.impulse-store-nav-btn').removeClass('is-default');
                    if (next) $btn.addClass('is-default');
                    saveTabPref({ default_store_section: next });
                    showTabToast(next ? '"' + $btn.text().trim() + '" is default Store tab' : 'Store default tab cleared');
                }, 600);
            });
            $(document).on('mouseup mouseleave', '.impulse-store-nav-btn', function() {
                if (timer) { clearTimeout(timer); timer = null; }
            });
            $(document).on('click', '.impulse-store-nav-btn', function(e) {
                if (fired) { e.stopImmediatePropagation(); fired = false; return false; }
            });
        })();

        (function() {
            var timer = null, fired = false;
            $(document).on('mousedown', '.impulse-device-tab', function(e) {
                if (e.button !== 0) return;
                var $btn = $(this);
                var device = $btn.data('device');
                fired = false;
                timer = setTimeout(function() {
                    fired = true;
                    var cur = Impulse.deviceDefault || '';
                    var next = (cur === device) ? '' : device;
                    Impulse.deviceDefault = next;
                    $('.impulse-device-tab').removeClass('is-default');
                    if (next) $btn.addClass('is-default');
                    saveTabPref({ default_device: next });
                    showTabToast(next ? '"' + $btn.text().trim() + '" is default device' : 'Default device cleared');
                }, 600);
            });
            $(document).on('mouseup mouseleave', '.impulse-device-tab', function() {
                if (timer) { clearTimeout(timer); timer = null; }
            });
            $(document).on('click', '.impulse-device-tab', function(e) {
                if (fired) { e.stopImmediatePropagation(); fired = false; return false; }
            });
        })();

        $(document).ready(function() {
            
            var storeDefault = Impulse.storeSectionDefault || '';
            if (storeDefault) {
                $('.impulse-store-nav-btn[data-store-section="' + storeDefault + '"]').addClass('is-default');
            }
            
            var deviceDefault = Impulse.deviceDefault || '';
            if (deviceDefault) {
                
                $(document).on('impulse:editor:opened', function() {
                    $('.impulse-device-tab[data-device="' + (Impulse.deviceDefault || '') + '"]').addClass('is-default');
                });
            }
        });

        $(document).on('impulse:workspace:store', function() {
            var def = Impulse.storeSectionDefault || '';
            if (def && typeof switchStoreSection === 'function') {
                switchStoreSection(def);
            }
        });
        
        $(document).on('impulse:editor:opened', function() {
            var def = Impulse.deviceDefault || '';
            if (def && typeof setDevice === 'function') {
                setDevice(def);
            }
            
            $('.impulse-device-tab').removeClass('is-default');
            if (def) $('.impulse-device-tab[data-device="' + def + '"]').addClass('is-default');
        });
    })();

    window._ctxData = null;
    window._ctxReleaseTimer = null;
    window._ctxOpen = false;
    window.ctxItem = function(action, label, shortcut, cls) {
        return '<div class="impulse-context-item' + (cls ? ' ' + cls : '') + '" data-action="' + action + '">' + label + (shortcut ? '<span class="shortcut">' + shortcut + '</span>' : '') + '</div>';
    };
    window.ctxDiv = function() { return '<div class="impulse-context-divider"></div>'; };
    window.ctxHide = function() {
        var $m = $('#impulse-context-menu');
        if ($m.is(':visible')) $m.hide();
        clearTimeout(window._ctxReleaseTimer);
        window._ctxOpen = false;
    };
    window.ctxShow = function($m, x, y, html) {
        $m.html(html).css({ left: -9999, top: -9999 }).show();
        var mw = $m.outerWidth() || 180, mh = $m.outerHeight() || 200;
        if (x + mw > window.innerWidth) x = window.innerWidth - mw - 10;
        if (y + mh > window.innerHeight) y = window.innerHeight - mh - 10;
        if (x < 0) x = 10; if (y < 0) y = 10;
        $m.css({ left: x, top: y });

        
        
        $m.addClass('is-opening');
        
        void $m[0].offsetHeight;
        requestAnimationFrame(function() {
            $m.removeClass('is-opening');
        });
        clearTimeout(window._ctxReleaseTimer);
        window._ctxOpen = true;
        window._ctxReleaseTimer = setTimeout(window.ctxHide, 3000);

        

        

        
        clearTimeout(window._ctxJustShownTimer);
        window._ctxJustShown = true;
        window._ctxJustShownTimer = setTimeout(function() {
            window._ctxJustShown = false;
        }, 300);
    };

    
    document.addEventListener('click', function(e) {
        if (!window._ctxOpen) return;
        
        if (e.target.closest && e.target.closest('#impulse-context-menu')) return;
        window.ctxHide();
    }, true);
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && window._ctxOpen) window.ctxHide();
    }, true);
    
    $(window).on('scroll', function() { if (window._ctxOpen) window.ctxHide(); });
    $(document).on('scroll', function() { if (window._ctxOpen) window.ctxHide(); });
    
    $('#impulse-context-menu').on('mouseenter', function() {
        clearTimeout(window._ctxReleaseTimer);
    }).on('mouseleave', function() {
        if (window._ctxOpen) window._ctxReleaseTimer = setTimeout(window.ctxHide, 3000);
    });

    
    function escapeHtml(str) {
        if (str == null) return '';
        return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    function impulseMarkdownToHtml(text) {
        if (!text) return '';
        
        if (/<(p|div|h[1-6]|ul|ol|li|blockquote|pre|hr|table)[\s>]/i.test(text)) return text;

        

        
        
        if (!/^#{1,6}[ \t]|^\*{2}|^[-*+][ \t]|^\d+\.[ \t]|^-{3,}[ \t]*$|^>[ \t]/m.test(text)) return text.replace(/\n/g, '<br>');

        var lines = text.replace(/\r\n/g, '\n').split('\n');
        var out = [], inUl = false, inOl = false, para = [];

        function flushPara() {
            if (para.length) { out.push('<p>' + para.join(' ') + '</p>'); para = []; }
        }
        function closeLists() {
            if (inUl) { out.push('</ul>'); inUl = false; }
            if (inOl) { out.push('</ol>'); inOl = false; }
        }
        function inline(s) {
            s = s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
            s = s.replace(/\*{3}(.+?)\*{3}/g, '<strong><em>$1</em></strong>');
            s = s.replace(/\*{2}(.+?)\*{2}/g, '<strong>$1</strong>');
            s = s.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '<em>$1</em>');
            s = s.replace(/`(.+?)`/g, '<code>$1</code>');
            s = s.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
            return s;
        }

        for (var i = 0; i < lines.length; i++) {
            var raw = lines[i].replace(/\s+$/, '');
            if (raw.trim() === '') { flushPara(); closeLists(); continue; }
            var m;
            if ((m = raw.match(/^(#{1,6})[ \t]+(.+)$/))) {
                flushPara(); closeLists();
                var lvl = m[1].length;
                out.push('<h' + lvl + '>' + inline(m[2]) + '</h' + lvl + '>');
            } else if (/^([-*_])\1{2,}[ \t]*$/.test(raw)) {
                flushPara(); closeLists(); out.push('<hr>');
            } else if ((m = raw.match(/^[-*+][ \t]+(.+)$/))) {
                flushPara();
                if (inOl) { out.push('</ol>'); inOl = false; }
                if (!inUl) { out.push('<ul>'); inUl = true; }
                out.push('<li>' + inline(m[1]) + '</li>');
            } else if ((m = raw.match(/^\d+\.[ \t]+(.+)$/))) {
                flushPara();
                if (inUl) { out.push('</ul>'); inUl = false; }
                if (!inOl) { out.push('<ol>'); inOl = true; }
                out.push('<li>' + inline(m[1]) + '</li>');
            } else if ((m = raw.match(/^>[ \t]*(.*)$/))) {
                flushPara(); closeLists();
                out.push('<blockquote>' + inline(m[1]) + '</blockquote>');
            } else {
                closeLists();
                para.push(inline(raw));
            }
        }
        flushPara(); closeLists();
        return out.join('\n');
    }

    
    function buildPageCard(id, name, permalink, status) {
        status = status || 'draft';
        var slug = permalink ? permalink.replace(/^.*\/([^\/]+)\/?$/, '$1') : '';
        var initials = name.substring(0, 2);
        var _logoUrl = (window.Impulse.pluginUrl || '') + 'assets/images/logo.svg';
        var card = $(
            '<div class="impulse-page-card" data-id="' + id + '" data-status="' + status + '" data-slug="' + escapeHtml(slug) + '" data-url="' + escapeHtml(permalink || '') + '">' +
            '<div class="impulse-page-preview" data-name="' + escapeHtml(name) + '">' +
                '<div class="impulse-card-check"><svg viewBox="0 0 24 24" width="14" height="14" color="currentColor"><g transform="scale(2.288)" fill="currentColor" stroke="none"><path d="M3.02 0.02l2.23 0c1.44,0 2.75,0.59 3.7,1.54 0.95,0.95 1.54,2.26 1.54,3.7 0,1.44 -0.59,2.75 -1.54,3.7 -0.95,0.95 -2.26,1.54 -3.7,1.54 -1.44,0 -2.75,-0.59 -3.7,-1.54 -0.95,-0.95 -1.54,-2.26 -1.54,-3.7l0 -2.23 2.31 0 0 2.23c0,0.8 0.33,1.53 0.86,2.06 0.53,0.53 1.26,0.86 2.06,0.86 0.8,0 1.53,-0.33 2.06,-0.86 0.53,-0.53 0.86,-1.26 0.86,-2.06 0,-0.8 -0.33,-1.53 -0.86,-2.06 -0.53,-0.53 -1.26,-0.86 -2.06,-0.86l-2.23 0 0 -2.31z"/><rect x="0.02" y="0.02" width="2.31" height="2.31"/></g></svg></div>' +
                '<div class="impulse-preview-placeholder" data-needs-thumb="1"><img src="' + _logoUrl + '" alt=""></div>' +
                '<div class="impulse-card-status' + (status === 'published' ? ' is-live' : '') + '" data-id="' + id + '" title="' + (status === 'published' ? 'Live - click to unpublish' : 'Draft - click to publish') + '">' +
                    '<span class="status-circle"></span>' +
                '</div>' +
            '</div>' +
            '<div class="impulse-page-info">' +
                '<div class="impulse-page-name" data-id="' + id + '">' +
                    '<span class="name-text" title="Click to rename">' + escapeHtml(name) + '</span>' +
                    '<input type="text" class="name-input" value="' + escapeHtml(name) + '" autocomplete="off">' +
                '</div>' +
            '</div>' +
            '</div>'
        );
        return card;
    }

    $('#impulse-new-page, #impulse-new-page-empty, #impulse-new-page-canvas, #impulse-new-screen-sequence').on('click', function() {

        

        $.ajax({
            url: Impulse.api + 'pages',
            method: 'POST',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            contentType: 'application/json',
            data: JSON.stringify({ name: '__auto__', settings: { bg_color: '#000000' } }),
            success: function(resp) {
                if (!resp.id) return;
                var autoTitle = 'Page ' + String(resp.id).padStart(4, '0');
                
                $.ajax({
                    url: Impulse.api + 'pages/' + resp.id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ name: autoTitle })
                });
                var $newCard = buildPageCard(resp.id, autoTitle, resp.permalink || '', 'draft');
                $('#impulse-canvas-grid').prepend($newCard);
                $('#impulse-canvas-empty').hide();
                updateTabCounts();
                openPageEditor(resp.id, autoTitle);
            },
            error: function(xhr) {
                var r = xhr && xhr.responseJSON;
                if (r && (r.error === 'page_limit' || r.upgrade)) {
                    if (window.triggerUpgradeCheckout) window.triggerUpgradeCheckout();
                    else if (window.showToast) window.showToast(r.message || 'Upgrade to Pro for unlimited pages', 'error');
                    return;
                }
                window.showToast && window.showToast('Failed to create scene', 'error');
            }
        });
    });

    $(document).on('click', '.impulse-open-page, .impulse-page-preview', function(e) {
        if (isDraggingCard) return;
        if ($(e.target).closest('.impulse-card-delete').length) return;
        if ($(e.target).closest('.impulse-card-status').length) return;
        var $card = $(this).closest('.impulse-page-card');
        var id = $card.data('id');
        var name = $card.find('.name-text').text();
        if (id && $card.data('status') !== 'trash') {
            openPageEditor(id, name);
        }
    });

    $(document).on('contextmenu', '#impulse-page-list', function(e) {
        if ($('.impulse-editor').hasClass('editing')) return;
        if (e.shiftKey) return;
        e.preventDefault();

        var $card = $(e.target).closest('.impulse-page-card');
        var cardId = $card.length ? $card.data('id') : 0;
        var cardName = $card.length ? ($card.find('.name-text').text() || '') : '';
        var cardSlug = $card.length ? ($card.data('slug') || '') : '';
        var isTrash = $card.length && $card.data('status') === 'trash';
        var isFront = $card.length && $card.hasClass('is-frontpage');

        var h = '';
        if (cardId && !isTrash) {
            h += ctxItem('grid-open', 'Open');
            h += ctxItem('grid-preview', 'Preview');
            h += ctxDiv();
            h += ctxItem('grid-export', 'Export');
            h += ctxItem('grid-duplicate', 'Duplicate');
            h += ctxItem('grid-history', 'History');

            
            h += ctxItem('grid-trash', 'Delete', '', 'danger');
            if (!isFront) {
                h += ctxItem('grid-frontpage', 'Set as Home Page');
            }

            
            
            h += ctxDiv();
        }
        if (cardId && isTrash) {
            h += ctxItem('grid-restore', 'Restore');
            h += ctxItem('grid-delete-permanent', 'Delete Forever', '', 'danger');
            h += ctxDiv();
        }
        h += ctxItem('grid-import', 'Import Page');

        _ctxData = { gridCard: cardId ? { id: cardId, name: cardName, slug: cardSlug } : null };
        ctxShow($('#impulse-context-menu'), e.clientX, e.clientY, h);
    });

    $(document).on('click', '.impulse-context-item[data-action^="grid-"]', function() {
        var action = $(this).data('action');
        var ctx = window._ctxData || {};
        ctxHide();

        

        switch (action) {
            case 'grid-open':
                if (ctx.gridCard) openPageEditor(ctx.gridCard.id, ctx.gridCard.name);
                break;
            case 'grid-export':
                if (ctx.gridCard) {
                    $.ajax({
                        url: Impulse.api + 'pages/' + ctx.gridCard.id + '/export',
                        method: 'GET',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function(data) {
                            var json = JSON.stringify(data, null, 2);
                            var blob = new Blob([json], { type: 'application/json' });
                            var a = document.createElement('a');
                            a.href = URL.createObjectURL(blob);
                            a.download = (data.page && data.page.slug ? data.page.slug : 'page-' + ctx.gridCard.id) + '.json';
                            a.click();
                            URL.revokeObjectURL(a.href);
                            window.showToast && window.showToast('Page exported');
                        },
                        error: function() { window.showToast && window.showToast('Export failed'); }
                    });
                }
                break;
            case 'grid-duplicate':
                if (ctx.gridCard) {
                    $.ajax({
                        url: Impulse.api + 'pages/' + ctx.gridCard.id + '/duplicate',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function() { location.reload(); },
                        error: function() { window.showToast && window.showToast('Duplicate failed'); }
                    });
                }
                break;
            case 'grid-history':
                if (ctx.gridCard) openPageHistory(ctx.gridCard.id, ctx.gridCard.name);
                break;
            case 'grid-trash':
                if (ctx.gridCard) {
                    var _trashId = ctx.gridCard.id;
                    $.ajax({
                        url: Impulse.api + 'pages/' + _trashId,
                        method: 'DELETE',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function() {
                            var $c = $('.impulse-page-card[data-id="' + _trashId + '"]');
                            $c.attr('data-status', 'trash').addClass('trashed').hide();
                            Impulse.pages = (Impulse.pages || []).filter(function(p){ return String(p.id) !== String(_trashId); });

                            window.showToast && window.showToast('Moved to trash');
                        },
                        error: function() { window.showToast && window.showToast('Trash failed'); }
                    });
                }
                break;
            case 'grid-preview':
                if (ctx.gridCard) {
                    window.open(window.Impulse.siteUrl + '?impulse_preview=' + ctx.gridCard.id, '_blank');
                }
                break;
            case 'grid-frontpage':
                if (ctx.gridCard) {
                    $.post(Impulse.ajaxUrl, {
                        action: 'instinctor_set_frontpage',
                        nonce: window.Impulse.adminNonce,
                        page_id: ctx.gridCard.id
                    }, function(r) {
                        if (r.success) {
                            $('.impulse-page-card.is-frontpage').each(function() {
                                var _fpId = $(this).data('id');
                                var _fpPg = Impulse.pages && Impulse.pages.find(function(p){ return String(p.id) === String(_fpId); });
                                var oldName = (_fpPg && _fpPg.name) || String($(this).find('.impulse-page-preview').data('name') || '');
                                $(this).find('.impulse-page-name').html(
                                    '<span class="name-text" title="Click to rename">' + escapeHtml(oldName) + '</span>' +
                                    '<input type="text" class="name-input" value="' + escapeHtml(oldName) + '" autocomplete="off">'
                                );
                            });
                            $('.impulse-page-card').removeClass('is-frontpage');
                            var $card = $('.impulse-page-card[data-id="' + ctx.gridCard.id + '"]');
                            $card.addClass('is-frontpage');
                            $card.find('.impulse-page-name').html(
                                '<span class="name-text" style="letter-spacing:0.08em;font-size:12px;font-weight:600">HOME PAGE</span>'
                            );
                            Impulse.frontPageId = ctx.gridCard.id;
                            
                            $.get(Impulse.api + 'pages', { _wpnonce: Impulse.nonce, per_page: 200 }, function(data) {
                                var pages = Array.isArray(data) ? data : (data.pages || []);
                                pages = pages.filter(function(p){ return p.type !== 'global_header' && p.type !== 'global_footer'; });
                                Impulse.pages = pages.map(function(p){
                                    return { id: p.id, name: p.name, slug: p.slug, screen_infinite_loop: !!p.screen_infinite_loop, thumbnail: p.thumbnail || '', permalink: p.permalink || '' };
                                });

                            });
                            window.showToast && window.showToast('Set as front page');
                        } else {
                            window.showToast && window.showToast('Failed');
                        }
                    });
                }
                break;
            case 'grid-restore':
                if (ctx.gridCard) {
                    $.ajax({
                        url: Impulse.api + 'pages/' + ctx.gridCard.id + '/restore',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function() { location.reload(); },
                        error: function() { window.showToast && window.showToast('Restore failed'); }
                    });
                }
                break;
            case 'grid-delete-permanent':
                if (ctx.gridCard) {
                    if (!window.impulseConfirm('Permanently delete this page?')) return;
                    var _permId = ctx.gridCard.id;
                    $.ajax({
                        url: Impulse.api + 'pages/' + _permId + '/permanent',
                        method: 'DELETE',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function() {
                            $('.impulse-page-card[data-id="' + _permId + '"]').remove();
                            Impulse.pages = (Impulse.pages || []).filter(function(p){ return String(p.id) !== String(_permId); });

                            window.showToast && window.showToast('Page deleted');
                        },
                        error: function() { window.showToast && window.showToast('Delete failed'); }
                    });
                }
                break;
            case 'grid-import':
                (function() {
                    var input = document.createElement('input');
                    input.type = 'file';
                    input.accept = '.json';
                    input.style.display = 'none';
                    input.onchange = function() {
                        var file = input.files[0];
                        if (!file) return;
                        var reader = new FileReader();
                        reader.onload = function(ev) {
                            try { var data = JSON.parse(ev.target.result); }
                            catch(err) { window.showToast && window.showToast('Invalid JSON'); return; }
                            $.ajax({
                                url: Impulse.api + 'pages/import',
                                method: 'POST',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify(data),
                                success: function(resp) {
                                    if (resp.success && resp.id) {
                                        window.showToast && window.showToast('Page imported');
                                        setTimeout(function() {
                                            window.location.href = (window.Impulse.adminBaseUrl + (window.Impulse.adminBaseUrl.indexOf('?') > -1 ? '&' : '?') + 'p=' + resp.id);
                                        }, 600);
                                    } else {
                                        window.showToast && window.showToast(resp.error || 'Import failed');
                                    }
                                },
                                error: function() { window.showToast && window.showToast('Import failed'); }
                            });
                        };
                        reader.readAsText(file);
                    };
                    document.body.appendChild(input);
                    input.click();
                    document.body.removeChild(input);
                })();
                break;
        }
    });

    $('#impulse-close-editor').on('click', function() {
        closePageEditor();
    });

    (function() {
        var $btn      = $('#impulse-page-switcher-btn');
        var $dropdown = $('#impulse-page-switcher-dropdown');
        var $switcher = $('#impulse-page-switcher');
        var _dismissTimer = null;

        function buildList(pages) {
            var currentId = Impulse.pageId;
            var html = '';
            pages.forEach(function(p) {
                var isCurrent = String(p.id) === String(currentId);
                var safeName = $('<div>').text(p.name).html();
                html += '<div class="impulse-page-switcher-item' + (isCurrent ? ' current' : '') + '" data-id="' + p.id + '" data-name="' + safeName + '">' +
                    '<span style="overflow:hidden;text-overflow:ellipsis">' + safeName + '</span>' +
                '</div>';
            });
            html += '<div class="impulse-page-switcher-item impulse-page-switcher-action" data-action="new-page" title="New page" style="color:#888;border-top:1px solid '+ImpC.panel+';margin-top:2px">+ New Page</div>';
            $dropdown.html(html);
        }

        function scheduleClose() {
            clearTimeout(_dismissTimer);
            _dismissTimer = setTimeout(close, 3000);
        }

        function open() {
            $dropdown.html('<div class="impulse-page-switcher-item" style="pointer-events:none;color:'+ImpC.dim+'">Loading\u2026</div>');
            $dropdown.addClass('open');
            $btn.addClass('active');
            scheduleClose();
            $.get(Impulse.api + 'pages', { _wpnonce: Impulse.nonce, per_page: 200 }, function(data) {
                var pages = Array.isArray(data) ? data : (data.pages || []);
                pages = pages.filter(function(p) {
                    return p.type !== 'global_header' && p.type !== 'global_footer';
                });
                Impulse.pages = pages.map(function(p) {
                    return { id: p.id, name: p.name, slug: p.slug, screen_infinite_loop: !!p.screen_infinite_loop, thumbnail: p.thumbnail || '', permalink: p.permalink || '' };
                });
                buildList(Impulse.pages);

            }).fail(function() {
                buildList(Impulse.pages || []);
            });
        }

        function close() {
            clearTimeout(_dismissTimer);
            $dropdown.removeClass('open');
            $btn.removeClass('active');
        }

        $btn.on('click', function(e) {
            e.stopPropagation();
            $dropdown.hasClass('open') ? close() : open();
        });

        $dropdown.on('mouseenter', function() { clearTimeout(_dismissTimer); });
        $dropdown.on('mouseleave', function() { scheduleClose(); });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('#impulse-page-switcher').length) close();
        });

        $(document).on('click', '.impulse-page-switcher-action', function(e) {
            e.stopPropagation();
            var action = $(this).data('action');
            close();
            if (action === 'new-page') {
                $('#impulse-new-page').trigger('click');
            }
        });

        $(document).on('click', '.impulse-page-switcher-item:not(.impulse-page-switcher-action)', function() {
            var id   = parseInt($(this).data('id'), 10);
            var name = $(this).data('name');
            if (id === Impulse.pageId) { close(); return; }
            close();
            openPageEditor(id, name);
        });

        $(document).on('impulse:editor:opened', function() {
            $switcher.show();
        });
    })();

    
    $('.impulse-canvas-tab').on('click', function() {
        var filter = $(this).data('filter');
        $('.impulse-canvas-tab').removeClass('active');
        $(this).addClass('active');
        
        var $grid = $('#impulse-canvas-grid');
        var $cards = $grid.find('.impulse-page-card');
        var $emptyTrashBtn = $('.impulse-canvas-empty-trash');

        
        var $posts = $cards.filter('[data-type="post"]');
        var $nonPosts = $cards.not('[data-type="post"]');

        if (filter === 'posts') {
            $cards.hide();
            $posts.filter('[data-status="published"], [data-status="draft"]').show();
            $emptyTrashBtn.hide();
        } else if (filter === 'all') {
            $posts.hide();
            $nonPosts.filter('[data-status="published"], [data-status="draft"]').show();
            $nonPosts.filter('[data-status="trash"]').hide();
            $emptyTrashBtn.hide();
        } else if (filter === 'trash') {
            $cards.hide();
            $cards.filter('[data-status="trash"]').show();
            $emptyTrashBtn.toggle($cards.filter('[data-status="trash"]').length > 0);
        } else {
            $cards.hide();
            $nonPosts.filter('[data-status="' + filter + '"]').show();
            $emptyTrashBtn.hide();
        }
    });

    
    function openPageHistory(pageId, pageName) {
        var $modal = $('#impulse-page-history-modal');
        var $body  = $('#impulse-page-history-body');
        $('#impulse-page-history-title').text('History — ' + (pageName || ('Page ' + pageId)));
        $body.html('<div style="padding:8px 0;color:#999">Loading…</div>');
        $modal.css('display', 'flex');

        $.ajax({
            url: Impulse.api + 'pages/' + pageId + '/revisions',
            method: 'GET',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            success: function(data) {
                var revs = (data && data.revisions) || [];
                if (!revs.length) {
                    $body.html('<div style="padding:8px 0;color:#999">No history yet — revisions will appear here as you save.</div>');
                    return;
                }
                var rows = revs.map(function(r) {
                    var when = (r.created_at || '').replace('T', ' ').replace(/\.[0-9]+Z?$/, '');
                    return '<div class="impulse-history-row" data-rev="' + r.id + '" style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid #2a2d31">'
                        +    '<span style="font-size:11px;color:#e0e0e0">' + escapeHtml(when) + ' <span style="color:#999;margin-left:8px">' + escapeHtml(r.kind || 'both') + '</span></span>'
                        +    '<button type="button" class="impulse-btn-sm impulse-history-restore" data-rev="' + r.id + '">Restore</button>'
                        + '</div>';
                }).join('');
                $body.html(rows);
            },
            error: function() {
                $body.html('<div style="padding:8px 0;color:#999">Failed to load revisions.</div>');
            }
        });

        $body.off('click.history').on('click.history', '.impulse-history-restore', function() {
            var revId = $(this).data('rev');
            var $btn = $(this).prop('disabled', true).text('Restoring…');
            $.ajax({
                url: Impulse.api + 'pages/' + pageId + '/revisions/' + revId + '/restore',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                success: function() {
                    window.showToast && window.showToast('Restored');
                    $modal.hide();
                    
                    if (Impulse.pageId === pageId && $('.impulse-editor').hasClass('editing')) {
                        location.reload();
                    } else {
                        location.reload();
                    }
                },
                error: function() {
                    window.showToast && window.showToast('Restore failed');
                    $btn.prop('disabled', false).text('Restore');
                }
            });
        });
    }

    function openPageEditor(pageId, pageName) {
        
        var _$pc = $('.impulse-page-card[data-id="' + pageId + '"]');
        if (_$pc.attr('data-type') === 'post') {
            window.location.href = '/admin/post/edit/' + pageId;
            return;
        }
        Impulse.pageId = pageId;
        
        $('.impulse-page-card').removeClass('is-open');
        $('.impulse-page-card[data-id="' + pageId + '"]').addClass('is-open');

        

        

        window._impulsePageEdited = false;
        (function keepOrPlaceholderThumbnail() {
            var $card = $('.impulse-page-card[data-id="' + pageId + '"]');
            var $preview = $card.find('.impulse-page-preview');
            if ($preview.length
                && !$preview.find('.impulse-preview-img').length
                && !$preview.find('.impulse-preview-placeholder').length) {
                $preview.find('.impulse-card-check').after('<div class="impulse-preview-placeholder" data-needs-thumb="1"><img src="' + (window.Impulse.pluginUrl || '') + 'assets/images/placeholder-logo.svg" alt=""></div>');
            }
        })();

        
        if ($('.impulse-editor').attr('data-workspace') !== 'impulse') {
            switchWorkspace('impulse');
        }

        if (!window.impulseEditorInitialized) {
            initEditor();
        }

        
        if (window.impulseResetEditorState) {
            window.impulseResetEditorState();
        }

        var newUrl = (window.Impulse.adminBaseUrl + (window.Impulse.adminBaseUrl.indexOf('?') > -1 ? '&' : '?') + 'p=' + pageId);
        history.pushState({ pageId: pageId }, '', newUrl);

        $('#impulse-page-name').text(pageName || 'Untitled');
        $('#impulse-page-name-input').val(pageName || 'Untitled');
        $('.impulse-page-name-edit').data('id', pageId);

        Impulse.pageSettings = {};
        var _iframeEl = document.getElementById('impulse-iframe');
        if (_iframeEl) { _iframeEl.style.transition = 'none'; _iframeEl.style.opacity = '0'; }
        if (typeof impulseShowLoadingBar === 'function') impulseShowLoadingBar();

        var $editor = $('.impulse-editor');
        $editor.removeClass('impulse-panels-entering');
        
        void $editor[0].offsetWidth;
        $editor.addClass('editing impulse-panels-entering').attr('data-page-id', pageId);
        setTimeout(function() { $editor.removeClass('impulse-panels-entering'); }, 900);

        $(document).trigger('impulse:editor:opened');

        $('.impulse-editing-only').show();
        $('.impulse-list-only').hide();
        $('.impulse-brand-name').hide();

        
        var _canvasOpen = document.querySelector('.impulse-canvas');
        if (_canvasOpen) _canvasOpen.style.cssText = '';
        $('.impulse-canvas').show().addClass('impulse-canvas-loading');
        $('.impulse-page-list').hide();

        

        
        
        var _openTs = Date.now();
        var _openPageId = pageId;
        var _settingsReady = false, _iframeLoaded = false;

        var _canvasEl0 = document.querySelector('.impulse-canvas');
        var _smEarly = true; 
        if (_canvasEl0) {
            _canvasEl0.setAttribute('data-screen-mode', _smEarly ? '1' : '0');
            _canvasEl0.style.background = _smEarly ? '#000000' : ''+ImpC.surface+'';
        }

        var _iframeDevice0 = window.impulseDevice || 'desktop';
        var _previewBase = (window.Impulse && window.Impulse.previewBaseUrl) ? window.Impulse.previewBaseUrl : '/admin/preview/';
        var _previewEditSuffix = (window.Impulse && window.Impulse.previewEditSuffix) ? window.Impulse.previewEditSuffix : '';
        var _previewSuffix = (window.Impulse && window.Impulse.previewBaseUrl && window.Impulse.previewBaseUrl.indexOf('impulse_preview=') !== -1) ? '&device=' : '?device=';
        var _iframeSrc0 = _previewBase + pageId + _previewEditSuffix + _previewSuffix + _iframeDevice0 + '&t=' + _openTs;
        var _iframeEl0 = document.getElementById('impulse-iframe');
        if (_iframeEl0) {
            
            _iframeEl0.style.height = '';
            _iframeEl0.src = _iframeSrc0;
        }

        

        

        
        
        function fitScreenCanvas() {
            var sm = Impulse.pageSettings && (true);
            var canvas = document.querySelector('.impulse-canvas');
            var scroll = document.querySelector('.impulse-canvas-scroll');
            if (!canvas || !scroll) return;

            if (!sm) {
                canvas.style.transform = '';
                canvas.style.transformOrigin = '';
                scroll.style.height = '';
                return;
            }
            
            if (typeof window._impulseRecomputeCanvasFit === 'function') {
                window._impulseRecomputeCanvasFit();
            }
        }
        window.fitScreenCanvas = fitScreenCanvas;
        var _fitTimer = null;
        $(window).on('resize.screenFit', function() {
            clearTimeout(_fitTimer);
            _fitTimer = setTimeout(fitScreenCanvas, 150);
        });

        if (window.ResizeObserver) {
            var _fitRo = new ResizeObserver(function() {
                clearTimeout(_fitTimer);
                _fitTimer = setTimeout(fitScreenCanvas, 60);
            });
            setTimeout(function() {
                var sc = document.querySelector('.impulse-canvas-scroll');
                var ifr = document.getElementById('impulse-iframe');
                if (sc) _fitRo.observe(sc);
                if (ifr) _fitRo.observe(ifr);
            }, 0);
        }

        function _applyOpenSettings(data) {
            if (data && data.settings) {
                try {
                    Impulse.pageSettings = typeof data.settings === 'string' ? JSON.parse(data.settings) : data.settings;
                } catch(e) { Impulse.pageSettings = {}; }
            }
            
            var _smNow = Impulse.pageSettings && (true);
            var _bgRaw = (Impulse.pageSettings && Impulse.pageSettings.bg_color) || '';
            var _bgNow = (_bgRaw && _bgRaw !== 'transparent') ? _bgRaw : (_smNow ? '#000000' : ''+ImpC.surface+'');
            var _canvasEl = document.querySelector('.impulse-canvas');
            if (_canvasEl) {
                _canvasEl.setAttribute('data-screen-mode', _smNow ? '1' : '0');
                _canvasEl.style.background = _bgNow;
                _canvasEl.classList.remove('impulse-canvas-loading');
            }
            if (data && data.permalink) {
                Impulse.pageSlug = data.slug || '';
                $('#impulse-page-slug-input').val(data.slug || '');
            }
            if (data && data.chat_hidden) {
                $('#instinctor-chat-widget-admin').addClass('page-chat-disabled');
            } else {
                $('#instinctor-chat-widget-admin').removeClass('page-chat-disabled');
            }
            var sm = true;
            var _smLoaded = !!(sm === '1' || sm === 1 || sm === true);
            $('.impulse-canvas').attr('data-screen-mode', _smLoaded ? '1' : '0');
            $('.impulse-panel-right').removeData('element-id');
            if (typeof window.showPageSettings === 'function') window.showPageSettings();

            
            if ((Impulse.pageSettings && (true))) {
                var _seedEff = Impulse.pageSettings.screen_cloud_effect || 'none';
                var _bgLockedLoad = ['cosmos','neon','caustics','glass','bubble','flow','aurora','clouds','aura','topography','lava','blob','fractal','noise','ripple','swirl','kaleidoscope'];
                var _paletteLoad = [];
                if (_seedEff !== 'none' && _bgLockedLoad.indexOf(_seedEff) === -1 && _paletteLoad.indexOf(_seedEff) === -1) {
                    var _effBgKey = 'screen_' + _seedEff + '_bg_color';
                    if (!Impulse.pageSettings[_effBgKey] && Impulse.pageSettings.bg_color && Impulse.pageSettings.bg_color !== 'transparent') {
                        Impulse.pageSettings[_effBgKey] = Impulse.pageSettings.bg_color;
                    }
                }
            }
            
            setTimeout(fitScreenCanvas, 300);
            
            if (_iframeLoaded && typeof applyPageSettingsToPreview === 'function') {
                applyPageSettingsToPreview(Impulse.pageSettings || {});
            }
        }

        $.get(Impulse.api + 'pages/' + pageId, { _wpnonce: Impulse.nonce }, function(data) {
            if (pageId !== _openPageId) return; 
            _settingsReady = true;
            _applyOpenSettings(data);
        }).fail(function() {
            if (pageId !== _openPageId) return;
            _settingsReady = true;
            Impulse.pageSettings = {};
            _applyOpenSettings(null);
        });

        $('.impulse-panel-tab').removeClass('active');
        $('.impulse-panel-tab[data-tab="blocks"]').addClass('active');
        $('.impulse-blocks-panel').show();
                $('#impulse-bug-report-bar').show();
        $('.impulse-structure-panel').hide();
        $('.impulse-templates-panel').hide();
        $('.impulse-search').show();
    }

    var pageSettingsSaveTimer = null;
    function closePageEditor() {
        var closingPageId = Impulse.pageId;

        
        
        var _retUrl = (function() {
            try {
                var p = new URLSearchParams(window.location.search).get('ret');
                if (!p) return '';
                var u = new URL(p, window.location.origin);
                if (u.origin === window.location.origin) return u.href;
                if (u.hostname === 'platform.instinctor.com') return u.href;
                return '';
            } catch (e) { return ''; }
        })();
        if (_retUrl) {

            
            if (typeof pageSettingsSaveTimer !== 'undefined' && pageSettingsSaveTimer && closingPageId && Impulse.pageSettings) {
                clearTimeout(pageSettingsSaveTimer);
                pageSettingsSaveTimer = null;
                try {
                    $.ajax({
                        url: Impulse.api + 'pages/' + closingPageId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: $.extend(true, {}, Impulse.pageSettings) }),
                        async: false
                    });
                } catch (e) {}
            }
            window.location.href = _retUrl;
            return;
        }
        
        var _cv = document.querySelector('.impulse-canvas');
        if (_cv) { _cv.style.transform = ''; _cv.style.transformOrigin = ''; }
        var _cs = document.querySelector('.impulse-canvas-scroll');
        if (_cs) { _cs.style.height = ''; }

        
        if (pageSettingsSaveTimer && closingPageId && Impulse.pageSettings) {
            clearTimeout(pageSettingsSaveTimer);
            pageSettingsSaveTimer = null;
            var flushSettings = $.extend(true, {}, Impulse.pageSettings);
            $.ajax({
                url: Impulse.api + 'pages/' + closingPageId,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ settings: flushSettings }),
                async: false  
            });
        }

        
        if (window._refreshDebounce) {
            for (var _rdk in window._refreshDebounce) { clearTimeout(window._refreshDebounce[_rdk]); }
            window._refreshDebounce = {};
        }
        
        if (window._autoSaveTimer) { clearTimeout(window._autoSaveTimer); window._autoSaveTimer = null; }

        

        

        

        
        var _closingCard = $('.impulse-page-card[data-id="' + closingPageId + '"]');
        var _thumbMissing = _closingCard.length ? (_closingCard.find('.impulse-preview-img').length === 0) : false;
        if (closingPageId && (window._impulsePageEdited || _thumbMissing)) {
            (function(pageId) {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentWindow) {
                    $('.impulse-canvas').hide();
                    return;
                }
                
                window._impulseCapturing = true;

                
                
                showThumbSpinner(pageId);

                var canvasEl = document.querySelector('.impulse-canvas');
                if (canvasEl) {
                    canvasEl.style.cssText = 'display:block!important;position:fixed!important;left:-9999px!important;top:0!important;width:1200px!important;height:800px!important;pointer-events:none!important;opacity:0!important;';
                }

                var _captureUrl = iframe.src.replace(/[?&]device=[^&]+/, '').replace(/[?&]t=\d+/, '');
                _captureUrl += (_captureUrl.indexOf('?') >= 0 ? '&' : '?') + 'device=desktop&t=' + Date.now();
                var _wasDesktop = iframe.src.indexOf('device=mobile') < 0 && iframe.src.indexOf('device=tablet') < 0;
                if (_wasDesktop) {
                    
                    try {
                        iframe.contentWindow.postMessage({ type: 'impulse-capture-thumbnail' }, '*');
                    } catch(e) {
                        if (canvasEl) { canvasEl.style.cssText = ''; canvasEl.style.display = 'none'; }
                        iframe.src = 'about:blank';
                        return;
                    }
                } else {
                    
                    iframe.onload = function() {
                        iframe.onload = null;
                        setTimeout(function() {
                            try {
                                iframe.contentWindow.postMessage({ type: 'impulse-capture-thumbnail' }, '*');
                            } catch(e) {
                                if (canvasEl) { canvasEl.style.cssText = ''; canvasEl.style.display = 'none'; }
                                iframe.src = 'about:blank';
                            }
                        }, 800); 
                    };
                    iframe.src = _captureUrl;
                }

                var done = false;
                function finish() {
                    if (done) return;
                    done = true;
                    window._impulseCapturing = false;
                    window.removeEventListener('message', onMsg);

                    

                    
                    hideThumbSpinner(pageId);
                    
                    if (canvasEl) canvasEl.style.cssText = '';
                    if (!Impulse.pageId) {
                        
                        if (canvasEl) canvasEl.style.display = 'none';
                        try { iframe.src = 'about:blank'; } catch(e) {}
                    }
                    
                }
                function onMsg(e) {
                    if (e.data && e.data.type === 'impulse-thumbnail-captured' && String(e.data.pageId) === String(pageId)) {
                        finish();
                    }
                }
                window.addEventListener('message', onMsg);
                
                setTimeout(finish, 10000);
            })(closingPageId);
        } else {
            $('.impulse-canvas').hide();
            $('#impulse-iframe').attr('src', 'about:blank');
        }

        $('#impulse-screen-bar').hide().html('');
        $('#impulse-screen-sidebar').hide();

        clearTimeout(pageSettingsSaveTimer);
        pageSettingsSaveTimer = null;
        $('#impulse-save-status').removeClass('saving').addClass('saved').text('Saved');

        var newUrl = window.Impulse.adminBaseUrl;
        history.pushState({}, '', newUrl);

        $('.impulse-editor').removeClass('editing').removeAttr('data-page-id');

        
        if (!window._impulseCapturing) {
            var _canvasClose = document.querySelector('.impulse-canvas');
            if (_canvasClose) _canvasClose.style.background = '';
        }

        $('.impulse-editing-only').hide();
        $('.impulse-list-only').each(function() {
            var display = $(this).hasClass('impulse-sequences-sidebar') ? 'flex' : '';
            $(this).css('display', display || '');
        });
        $('.impulse-brand-name').show();

        if (closingPageId) {
            var closingName = $('#impulse-page-name').text();
            if (closingName && closingName !== 'Untitled') {
                var $closingCard = $('.impulse-page-card[data-id="' + closingPageId + '"]');
                $closingCard.find('.name-text').text(closingName);
                $closingCard.find('.name-input').val(closingName);
            }
        }

        $('.impulse-page-list').show();

        
        
        if (typeof selectedElementId !== 'undefined') {
            selectedElementId = null;
        }
        
        Impulse.pageId = null;
    }

    

    
    function showThumbSpinner(pageId) {
        if (!pageId) return;
        var $preview = $('.impulse-page-card[data-id="' + pageId + '"] .impulse-page-preview');
        if (!$preview.length || $preview.find('.impulse-thumb-spinner').length) return;
        $preview.append('<div class="impulse-thumb-spinner" aria-label="Generating thumbnail"></div>');
    }
    function hideThumbSpinner(pageId) {
        if (!pageId) {
            $('.impulse-thumb-spinner').remove();
            return;
        }
        $('.impulse-page-card[data-id="' + pageId + '"] .impulse-thumb-spinner').remove();
    }

    function saveThumbnailToServer(pageId, dataUrl, callback) {
        $.ajax({
            url: Impulse.api + 'pages/' + pageId + '/thumbnail',
            method: 'POST',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            contentType: 'application/json',
            data: JSON.stringify({ thumbnail: dataUrl }),
            success: function(resp) {
                var imgUrl = resp.url;
                if (imgUrl) {
                    
                    var $card = $('.impulse-page-card[data-id="' + pageId + '"]');
                    var $img = $card.find('.impulse-preview-img');
                    if ($img.length) {
                        $img.attr('src', imgUrl);
                    } else {
                        var $preview = $card.find('.impulse-page-preview');
                        $preview.find('.impulse-preview-placeholder, .impulse-preview-iframe-wrap').remove();
                        $preview.find('.impulse-card-check').after('<img src="' + imgUrl + '" class="impulse-preview-img" alt="">');
                    }
                }
                if (callback) callback(true);
            },
            error: function(xhr) {
                if (callback) callback(false);
            }
        });
    }

    window.addEventListener('message', function(e) {
        if (e.data.type !== 'impulse-thumbnail-captured') return;
        var dataUrl = e.data.dataUrl;
        var pageId = e.data.pageId;
        if (!dataUrl || !pageId) return;

        
        (function updateCardNow() {
            var $card = $('.impulse-page-card[data-id="' + pageId + '"]');
            var $preview = $card.find('.impulse-page-preview');
            if ($preview.length) {
                $preview.find('.impulse-preview-placeholder, .impulse-preview-img, .impulse-preview-iframe-wrap').remove();
                $preview.find('.impulse-card-check').after('<img src="' + dataUrl + '" class="impulse-preview-img" alt="">');
            }
        })();

        saveThumbnailToServer(pageId, dataUrl);
    });

    window.addEventListener('popstate', function(e) {
        if (e.state && e.state.pageId) {
            openPageEditor(e.state.pageId);
        } else {
            closePageEditor();
        }
    });

    $('.impulse-modal-close').on('click', function() {
        $(this).closest('.impulse-modal').hide();
    });

    $('.impulse-modal').on('click', function(e) {
        if ($(e.target).is('.impulse-modal')) {
            $(this).hide();
        }
    });

    $('.impulse-page-tab').on('click', function() {
        var filter = $(this).data('filter');
        $('.impulse-page-tab').removeClass('active');
        $(this).addClass('active');
        
        var $grid = $('#impulse-pages-grid');
        var $cards = $grid.find('.impulse-page-card');
        var $trashEmpty = $grid.find('.impulse-trash-empty');
        var $emptyState = $grid.find('.impulse-empty-state:not(.impulse-trash-empty)');
        var $emptyTrashBtn = $('#impulse-empty-trash');
        
        if (filter === 'all') {
            $cards.filter('[data-status="published"], [data-status="draft"]').show();
            $cards.filter('[data-status="trash"]').hide();
            $trashEmpty.hide();
            $emptyState.toggle($cards.filter('[data-status="published"], [data-status="draft"]').length === 0);
            $emptyTrashBtn.hide();
        } else if (filter === 'trash') {
            $cards.filter('[data-status="published"], [data-status="draft"]').hide();
            $cards.filter('[data-status="trash"]').show();
            $emptyState.hide();
            $trashEmpty.toggle($cards.filter('[data-status="trash"]').length === 0);
            
            $emptyTrashBtn.toggle($cards.filter('[data-status="trash"]').length > 0);
        } else {
            $cards.hide();
            $cards.filter('[data-status="' + filter + '"]').show();
            $trashEmpty.hide();
            $emptyState.toggle($cards.filter('[data-status="' + filter + '"]').length === 0);
            $emptyTrashBtn.hide();
        }
    });

    $('#impulse-card-size').on('input', function() {
        var size = $(this).val();
        $('#impulse-canvas-grid').css('--card-size', size + 'px');
        localStorage.setItem('impulse-card-size', size);
    });

    

    

    (function() {
        var btn = document.getElementById('impulse-cellborders-toggle');
        if (!btn) return;
        var KEY = 'impulse_show_cell_borders';
        function isOn() { return sessionStorage.getItem(KEY) === '1'; }
        function applyToIframe(retry) {
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe && (iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document));
            if (!doc || !doc.body) {

                
                if ((retry || 0) < 6) setTimeout(function(){ applyToIframe((retry || 0) + 1); }, 80);
                return;
            }
            doc.body.classList.toggle('impulse-show-cell-borders', isOn());
        }
        function applyToButton() {
            btn.classList.toggle('is-active', isOn());
            btn.setAttribute('title', isOn()
                ? 'Cell guides ON — click to hide'
                : 'Cell guides OFF — click to show');
        }
        btn.addEventListener('click', function() {
            sessionStorage.setItem(KEY, isOn() ? '0' : '1');
            applyToButton();
            applyToIframe();
        });

        
        var iframe = document.getElementById('impulse-iframe');
        if (iframe) {
            iframe.addEventListener('load', function() {
                applyToButton();
                applyToIframe();
            });
        }
        applyToButton();
        
        setTimeout(applyToIframe, 100);
    })();

    

    

    

    

    

    
    window._impulseFitScale = 1;
    (function() {
        var canvas = document.querySelector('.impulse-canvas');
        if (!canvas) return;
        var scroll = document.querySelector('.impulse-canvas-scroll');

        function computeFitScale() {
            if (canvas.getAttribute('data-screen-mode') !== '1' || !scroll) {
                window._impulseFitScale = 1;
                window._impulseFitValid = true; 
                return;
            }

            

            

            
            
            var cw = canvas.offsetWidth, ch = canvas.offsetHeight;
            var pad = 40; 
            var availW = scroll.clientWidth  - pad;
            var availH = scroll.clientHeight - pad;
            if (availW <= 0 || availH <= 0 || cw <= 0 || ch <= 0) { window._impulseFitScale = 1; window._impulseFitValid = false; return; }
            var fit = Math.min(availW / cw, availH / ch);
            window._impulseFitScale = Math.max(0.1, Math.min(2, fit));
            window._impulseFitValid = true;
        }

        function applyTransform() {
            var n = window._impulseFitScale || 1;

            
            
            if (canvas.getAttribute('data-screen-mode') === '1') {
                canvas.style.transform = 'translate(-50%, -50%) scale(' + n.toFixed(3) + ')';

                
                if (window._impulseFitValid) canvas.classList.add('impulse-canvas-fitted');
            } else {
                canvas.style.transform = n === 1 ? '' : 'scale(' + n.toFixed(3) + ')';
                canvas.classList.add('impulse-canvas-fitted'); 
            }

            

            
            
            try {
                var _ifWin = ifr && ifr.contentWindow;
                if (_ifWin) {
                    _ifWin._impulseEditorScale = n;
                    _ifWin.postMessage({ type: 'impulse-canvas-scale', scale: n }, '*');
                }
            } catch (_e) {}
        }

        function recompute() {
            computeFitScale();
            applyTransform();
        }

        

        
        
        var _fitTries = 0;
        (function ensureFitted() {
            recompute();
            if (window._impulseFitValid && canvas.classList.contains('impulse-canvas-fitted')) return;
            if (_fitTries++ < 180) { requestAnimationFrame(ensureFitted); return; }
            canvas.classList.add('impulse-canvas-fitted'); 
        })();
        window.addEventListener('resize', recompute);
        var ifr = document.getElementById('impulse-iframe');
        if (ifr) ifr.addEventListener('load', recompute);

        $(document).on('click', '.impulse-device-tab', function() {

            setTimeout(recompute, 16);
        });

        
        
        window._impulseRecomputeCanvasFit = recompute;
    })();

    var savedSize = localStorage.getItem('impulse-card-size');
    if (savedSize) {
        $('#impulse-card-size').val(savedSize);
        $('#impulse-canvas-grid').css('--card-size', savedSize + 'px');
    }

    

    $(document).on('click', '#impulse-mobile-optimize-btn', function() {
        if (!Impulse.pageId) return;
        var btn = this;
        btn.disabled = true;
        btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg> Analyzing\u2026';
        
        $.ajax({
            url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
            method: 'GET',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            success: function(resp) {
                try {
                    var elements = (resp && resp.elements) || resp || [];
                    if (!Array.isArray(elements)) {
                        console.error('[Mobile optimizer] unexpected response shape', resp);
                        if (typeof showToast === 'function') showToast('Mobile optimizer: unexpected response shape.', 'error');
                    } else {
                        console.log('[Mobile optimizer] fetched ' + elements.length + ' elements');
                        var changes = computeMobileOptimizations(elements, Impulse.pageSettings || {});
                        console.log('[Mobile optimizer] computed ' + changes.totalChanges + ' proposed changes');
                        showMobileOptimizerModal(changes, elements);
                    }
                } catch (err) {
                    console.error('[Mobile optimizer] JS error', err);
                    if (typeof showToast === 'function') showToast('Mobile optimizer crashed: ' + (err && err.message ? err.message : 'unknown'), 'error');
                }
                btn.disabled = false;
                btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg> Optimize for Mobile';
            },
            error: function(xhr) {
                console.error('Mobile optimizer: failed to load elements', xhr.status, xhr.responseText);
                btn.disabled = false;
                btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg> Optimize for Mobile';
                
                if (typeof showToast === 'function') {
                    showToast('Mobile optimizer failed (' + (xhr.status || 'network') + '). Try a hard-refresh.', 'error');
                }
            }
        });
    });
    
    function moScale(val, breakpoints) {
        for (var i = 0; i < breakpoints.length; i++) {
            if (val >= breakpoints[i][0]) return Math.round(val * breakpoints[i][1]);
        }
        return val;
    }
    
    function moProposeBoth(s, key, tabletVal, mobileVal, mods) {

        

        

        
        var TOLERANCE = 1.4;

        function shouldPropose(existing, proposed) {
            if (existing === undefined || existing === '' || existing === null) return true;
            var pn = parseFloat(proposed);
            var en = parseFloat(existing);
            if (isNaN(en)) return true;
            
            if (en === 0 && pn !== 0) return false;

            return Math.abs(en) > Math.abs(pn) * TOLERANCE;
        }

        if (shouldPropose(s[key + '_tablet'], tabletVal)) mods[key + '_tablet'] = tabletVal;
        if (shouldPropose(s[key + '_mobile'], mobileVal)) mods[key + '_mobile'] = mobileVal;
        return true;
    }
    
    function computeMobileOptimizations(elements, pageSettings) {
        var changes = { page: {}, elements: {} };
        var totalChanges = 0;
        var ps = pageSettings || {};

        

        var isScreenMode = (true);

        

        var fontBreaks = [
            [150, 0.18], [120, 0.22], [100, 0.26], [80, 0.32], [64, 0.38],
            [48, 0.45], [36, 0.55], [28, 0.65], [22, 0.75], [18, 0.85]
        ];
        var fontBreaksT = [
            [150, 0.35], [120, 0.40], [100, 0.45], [80, 0.50], [64, 0.55],
            [48, 0.62], [36, 0.72], [28, 0.82], [22, 0.88]
        ];

        var padBreaks  = isScreenMode
            ? [[100, 0.22], [80, 0.25], [60, 0.30], [40, 0.40], [24, 0.55], [16, 0.70]]
            : [[100, 0.35], [80, 0.40], [60, 0.45], [40, 0.55], [24, 0.65], [16, 0.80]];
        var padBreaksT = isScreenMode
            ? [[100, 0.45], [80, 0.50], [60, 0.55], [40, 0.65], [24, 0.75]]
            : [[100, 0.55], [80, 0.60], [60, 0.65], [40, 0.75], [24, 0.85]];
        var gapBreaks  = [[60, 0.35], [40, 0.45], [24, 0.55], [16, 0.65], [12, 0.75]];
        var gapBreaksT = [[60, 0.55], [40, 0.65], [24, 0.75], [16, 0.85]];
        var marginBreaks = [[100, 0.25], [60, 0.35], [40, 0.45], [24, 0.55], [16, 0.7]];
        var marginBreaksT = [[100, 0.45], [60, 0.55], [40, 0.65], [24, 0.75], [16, 0.85]];

        
        var childrenByParent = {};
        (elements || []).forEach(function(el) {
            var p = el.parent_id || el.parentId || 0;
            if (!p) return;
            (childrenByParent[p] = childrenByParent[p] || []).push(el);
        });

        

        function mobileColsFor(desktopCols, childCount) {
            var n = Math.max(parseInt(desktopCols) || 1, parseInt(childCount) || 0);
            if (n <= 2) return 1;          
            if (n <= 5) return 2;          
            return 3;                      
        }
        function tabletColsFor(desktopCols, childCount) {
            var n = Math.max(parseInt(desktopCols) || 1, parseInt(childCount) || 0);
            if (n <= 1) return 1;
            if (n <= 3) return 2;
            return 3;
        }

        

        
        var fontKeys = ['font_size','title_size','subtitle_size','heading_size','text_size','description_size',
            'price_size','content_size','label_size','button_font_size','menu_font_size',
            'front_title_size','front_content_size','back_title_size','back_content_size',
            'element_text_size','number_size','checkout_btn_size','size',
            'counter_size','prefix_size','suffix_size','badge_size','tag_size',
            'field_font_size','placeholder_size','la_font_size','name_size','role_size',
            'stat_size','stat_label_size','quote_size','author_size'];
        var padKeys = ['padding_top','padding_bottom','padding_left','padding_right',
            'padding','padding_x','padding_y','inner_padding','box_padding','section_padding',
            'padding_sides','card_padding','cell_padding','item_padding',
            'cell_padding_h','cell_padding_v','slide_padding',
            'content_padding','header_padding'];
            
        var gapKeys = ['gap','row_gap','column_gap','col_gap','item_gap','cell_gap','spacing',
            'gap_horizontal','gap_vertical','element_spacing','text_spacing','field_gap','icon_gap',
            'card_gap','grid_gap','list_gap','button_gap','feature_gap'];
        var marginKeys = ['margin_top','margin_bottom','margin_left','margin_right'];
        var heightKeys = ['min_height','height','max_height','field_height','card_height','row_height',
            'item_height','box_height','container_height'];
        var widthKeys = ['max_width','section_max_width','content_max_width','card_width',
            'min_card_width','container_width','box_width'];
        
        (elements || []).forEach(function(el) {
            var s = el.settings || {};
            var type = el.type || el.section_type || '';
            var mods = {};

            
            
            fontKeys.forEach(function(key) {
                var v = parseInt(s[key]);
                if (v && v >= 16) moProposeBoth(s, key, moScale(v, fontBreaksT), moScale(v, fontBreaks), mods);
            });

            

            

            if (type === 'section') {
                padKeys.forEach(function(key) {
                    var v = parseInt(s[key]);
                    if (v && v >= 16) moProposeBoth(s, key, moScale(v, padBreaksT), moScale(v, padBreaks), mods);
                });
            }

            

            gapKeys.forEach(function(key) {
                var v = parseInt(s[key]);
                if (v && v > 8) moProposeBoth(s, key, moScale(v, gapBreaksT), moScale(v, gapBreaks), mods);
            });

            
            
            marginKeys.forEach(function(key) {
                var v = parseInt(s[key]);
                if (v && Math.abs(v) >= 16) {
                    var sign = v < 0 ? -1 : 1;
                    var av = Math.abs(v);
                    moProposeBoth(s, key,
                        sign * moScale(av, marginBreaksT),
                        sign * moScale(av, marginBreaks), mods);
                }
            });

            
            
            heightKeys.forEach(function(key) {
                var v = parseInt(s[key]);
                if (v && v > 200) moProposeBoth(s, key, Math.round(v * 0.75), Math.round(v * 0.55), mods);
            });

            
            
            widthKeys.forEach(function(key) {
                var v = parseInt(s[key]);
                if (v && v > 0 && type !== 'modal') {
                    moProposeBoth(s, key, v, 0, mods);
                }
            });

            
            
            var ls = parseInt(s.letter_spacing);
            if (ls && Math.abs(ls) > 1) moProposeBoth(s, 'letter_spacing', Math.round(ls * 0.6), Math.round(ls * 0.3), mods);

            
            
            var br = parseInt(s.border_radius);
            if (br && br > 16) moProposeBoth(s, 'border_radius', Math.min(br, 14), Math.min(br, 10), mods);

            
            
            if (type === 'section') {
                var cw = parseInt(s.content_width);
                if (cw && cw < 90) moProposeBoth(s, 'content_width', Math.max(cw, 95), 100, mods);
            }

            
            
            if (type === 'title') {
                for (var li = 1; li <= 3; li++) {
                    var lk = 'line_' + li + '_size';
                    var lv = parseInt(s[lk]);
                    if (lv && lv >= 16) moProposeBoth(s, lk, moScale(lv, fontBreaksT), moScale(lv, fontBreaks), mods);
                    var dk = 'line_' + li + '_depth';
                    var dv = parseInt(s[dk]);
                    if (dv) moProposeBoth(s, dk, Math.round(dv * 0.4), 0, mods);
                }
                var persp = parseInt(s.perspective);
                if (persp && persp > 0) moProposeBoth(s, 'perspective', Math.round(persp * 0.4), 0, mods);
                var dof = parseInt(s.dof_intensity);
                if (dof && dof > 0) moProposeBoth(s, 'dof_intensity', Math.round(dof * 0.4), 0, mods);
            }

            
            
            if (type === 'title') {
                var laIw = parseInt(s.la_image_width);
                if (laIw && laIw > 120) moProposeBoth(s, 'la_image_width', Math.round(laIw * 0.6), Math.round(laIw * 0.4), mods);
            }

            
            
            if (type === 'image') {
                var iw = parseInt(s.width);
                if (iw && iw < 100) moProposeBoth(s, 'width', Math.max(iw, 90), 100, mods);
            }

            
            
            if (type === 'video') {
                var vw = parseInt(s.width);
                if (vw && vw < 100) moProposeBoth(s, 'width', Math.max(vw, 92), 100, mods);
                var ar = s.aspect_ratio || '16:9';
                if (ar === '9:16') moProposeBoth(s, 'aspect_ratio', '4:3', '16:9', mods);
            }

            
            
            if (type === 'button') {
                var bpx = parseInt(s.padding_x);
                if (bpx && bpx > 20) moProposeBoth(s, 'padding_x', Math.round(bpx * 0.7), Math.round(bpx * 0.55), mods);
            }

            

            

            if (type === 'icon_card') {
                
                var iconParentCols = 1;
                var p = el.parent_id || el.parentId;
                while (p) {
                    var parentEl = null;
                    for (var pi = 0; pi < elements.length; pi++) {
                        if (String(elements[pi].id) === String(p)) { parentEl = elements[pi]; break; }
                    }
                    if (!parentEl) break;
                    if (parentEl.type === 'grid' || parentEl.type === 'rows' || parentEl.type === 'columns') {
                        var pMod = (changes.elements[parentEl.id] && changes.elements[parentEl.id].mods) || {};
                        var raw = pMod.columns_mobile !== undefined ? pMod.columns_mobile
                                : (parentEl.settings || {}).columns_mobile;
                        if (raw) iconParentCols = Math.max(1, parseInt(raw) || 1);
                        else if (parentEl.type !== 'grid') iconParentCols = Math.max(1, parseInt(pMod.columns || (parentEl.settings || {}).columns) || 1);
                        break;
                    }
                    p = parentEl.parent_id || parentEl.parentId;
                }

                
                
                var ics = parseInt(s.size);
                if (ics && ics > 36) {
                    var sM = iconParentCols >= 3 ? 0.45 : iconParentCols >= 2 ? 0.55 : 0.70;
                    moProposeBoth(s, 'size', Math.round(ics * 0.70), Math.round(ics * sM), mods);
                }
                
                var its = parseInt(s.title_size);
                if (its && its > 14) {
                    var titleMob = iconParentCols >= 3 ? Math.max(13, Math.round(its * 0.55))
                                : iconParentCols >= 2 ? Math.max(14, Math.round(its * 0.65))
                                : Math.max(16, Math.round(its * 0.75));
                    moProposeBoth(s, 'title_size', Math.round(its * 0.85), titleMob, mods);
                }
                
                var its2 = parseInt(s.text_size);
                if (its2 && its2 > 12) {
                    var bodyMob = iconParentCols >= 3 ? 12
                                : iconParentCols >= 2 ? Math.max(12, Math.round(its2 * 0.80))
                                : Math.max(13, Math.round(its2 * 0.90));
                    moProposeBoth(s, 'text_size', Math.round(its2 * 0.90), bodyMob, mods);
                }

                var ibp = parseInt(s.ib_perspective);
                if (ibp && ibp > 0) moProposeBoth(s, 'ib_perspective', Math.round(ibp * 0.4), 0, mods);
                ['ib_icon_depth','ib_title_depth','ib_text_depth'].forEach(function(dk) {
                    var dv = parseInt(s[dk]);
                    if (dv) moProposeBoth(s, dk, Math.round(dv * 0.4), 0, mods);
                });
            }

            

            

            
            if (type === 'grid' || type === 'rows' || type === 'columns') {
                var kids = (childrenByParent[el.id] || []).length;
                var dCols = parseInt(s.columns) || 0;
                var mCols = mobileColsFor(dCols, kids);
                var tCols = tabletColsFor(dCols, kids);

                if (type === 'grid') {

                    

                    
                    
                    if (mCols >= 2) {
                        if (!s.columns_mobile || parseInt(s.columns_mobile) !== mCols) {
                            mods.columns_mobile = String(mCols);
                        }
                    }
                    if (tCols && (!s.columns_tablet || parseInt(s.columns_tablet) !== tCols)) {
                        mods.columns_tablet = String(tCols);
                    }
                } else {
                    
                    if (dCols && dCols !== tCols) moProposeBoth(s, 'columns', tCols, mCols, mods);
                }
            }

            
            
            if (type === 'slider') {
                var sts = parseInt(s.slides_to_show);
                if (sts && sts > 1) moProposeBoth(s, 'slides_to_show', 1, 1, mods);
                if (!s.mobile_stack || s.mobile_stack === '0') mods.mobile_stack = '1';
            }

            

            
            if (type === 'products') {
                var ipr = parseInt(s.items_per_row || s.products_per_row);
                if (ipr && ipr >= 2) {
                    var pMobile = ipr >= 4 ? 2 : 1;
                    var pTablet = ipr >= 3 ? Math.min(ipr, 3) : 2;
                    moProposeBoth(s, 'items_per_row', pTablet, pMobile, mods);
                }
                var ppr = parseInt(s.products_per_row);
                if (ppr && ppr >= 2) {
                    var ppMobile = ppr >= 4 ? 2 : 1;
                    var ppTablet = ppr >= 3 ? Math.min(ppr, 3) : 2;
                    moProposeBoth(s, 'products_per_row', ppTablet, ppMobile, mods);
                }
            }

            
            
            if (type === 'unfold') {
                var aw = parseInt(s.acc_width);
                if (aw && aw < 100) moProposeBoth(s, 'acc_width', Math.max(aw, 90), 100, mods);
                var sr = parseInt(s.split_ratio);
                if (sr && sr !== 50) moProposeBoth(s, 'split_ratio', 50, 50, mods);
                var pk = parseInt(s.peek_offset);
                if (pk && pk > 20) moProposeBoth(s, 'peek_offset', Math.round(pk * 0.7), Math.round(pk * 0.5), mods);

                var itt = parseInt(s.item_title_size);
                if (itt && itt > 16) moProposeBoth(s, 'item_title_size', Math.min(itt, 20), Math.min(itt, 16), mods);
                var itb = parseInt(s.item_body_size);
                if (itb && itb > 14) moProposeBoth(s, 'item_body_size', Math.min(itb, 16), Math.min(itb, 14), mods);
            }

            

            if (type === 'flip_box') {
                var fh = parseInt(s.height);
                if (fh && fh > 180) moProposeBoth(s, 'height', Math.round(fh * 0.75), Math.round(fh * 0.6), mods);
            }

            
            
            if (type === 'carousel') {
                var gKids = (childrenByParent[el.id] || []).length;
                var gc = parseInt(s.columns);
                if (gc && gc >= 2) {
                    moProposeBoth(s, 'columns', tabletColsFor(gc, gKids), mobileColsFor(gc, gKids), mods);
                }
                var gits = parseInt(s.items_to_show);
                if (gits && gits >= 2) moProposeBoth(s, 'items_to_show', Math.min(gits, 2), 1, mods);
            }

            

            if (type === 'plans') {
                var planKids = (childrenByParent[el.id] || []).length;
                var ptc = parseInt(s.columns);
                if (ptc && ptc >= 2) {
                    var totalPlans = Math.max(ptc, planKids);
                    moProposeBoth(s, 'columns',
                        totalPlans >= 4 ? 2 : 2,
                        totalPlans >= 4 ? 2 : 1, mods);
                }
            }

            
            
            if (type === 'social') {
                var sis = parseInt(s.icon_size);
                if (sis && sis > 28) moProposeBoth(s, 'icon_size', Math.round(sis * 0.8), Math.round(sis * 0.65), mods);
            }

            
            
            if (type === 'divider') {
                var dw = parseInt(s.width);
                if (dw && dw < 100) moProposeBoth(s, 'width', 100, 100, mods);
            }

            

            
            
            if (type === 'header') {
                var lh = parseInt(s.logo_height);
                if (lh && lh > 32) moProposeBoth(s, 'logo_height', Math.min(lh, 34), Math.min(lh, 28), mods);
                var avs = parseInt(s.avatar_size);
                if (avs && avs > 50) moProposeBoth(s, 'avatar_size', Math.round(avs * 0.8), Math.round(avs * 0.65), mods);
            }

            
            
            if (type === 'product_carousel') {
                var pcCols = parseInt(s.columns || s.visible_count);
                if (pcCols && pcCols >= 2) moProposeBoth(s, 'columns', 2, 1, mods);
            }

            
            
            if (type === 'bundle') {
                var bw = parseInt(s.bundle_width);
                if (bw && bw > 320) moProposeBoth(s, 'bundle_width', Math.min(bw, 360), 320, mods);
            }

            
            
            if (type === 'table') {
                var ilCols = parseInt(s.columns);
                if (ilCols && ilCols > 1) moProposeBoth(s, 'columns', Math.min(ilCols, 2), 1, mods);
            }

            
            
            if (type === 'login' || type === 'register' || type === 'contact_form') {
                var fmw = parseInt(s.form_width || s.width);
                if (fmw && fmw < 100) moProposeBoth(s, s.form_width !== undefined ? 'form_width' : 'width', Math.max(fmw, 90), 100, mods);
            }
            
            if (Object.keys(mods).length) {
                changes.elements[el.id] = {
                    type: type,
                    mods: mods,
                    name: s.struct_label || s.label || s.la_text || s.line_1 || s.title || type
                };
                totalChanges += Object.keys(mods).length;
            }
        });

        

        

        
        
        var FLOOR_BODY  = 14;   
        var FLOOR_ICON  = 12;   
        var FLOOR_TITLE = 16;   
        function ensureFloor(elId, type, keys, floor) {
            var origEl = null;
            for (var i = 0; i < (elements || []).length; i++) {
                if (String(elements[i].id) === String(elId)) { origEl = elements[i]; break; }
            }
            if (!origEl) return;
            var s = origEl.settings || {};
            var existingMods = (changes.elements[elId] && changes.elements[elId].mods) || {};
            keys.forEach(function(key) {
                var mk = key + '_mobile';
                
                var raw = (mk in existingMods) ? existingMods[mk] : s[mk];
                var n = parseInt(raw);
                if (!isNaN(n) && n > 0 && n < floor) {
                    
                    if (!changes.elements[elId]) {
                        changes.elements[elId] = {
                            type: type,
                            name: (s.struct_label || s.label || s.la_text || s.line_1 || s.title || type),
                            mods: {}
                        };
                    }
                    if (!(mk in changes.elements[elId].mods)) totalChanges++;
                    changes.elements[elId].mods[mk] = floor;
                }
            });
        }
        (elements || []).forEach(function(el) {
            var t = el.type;
            if (t === 'text')   ensureFloor(el.id, t, ['size', 'font_size'], FLOOR_BODY);
            if (t === 'icon_card')   {
                ensureFloor(el.id, t, ['text_size'], FLOOR_ICON);
                ensureFloor(el.id, t, ['title_size'], FLOOR_TITLE);
            }
            if (t === 'title') ensureFloor(el.id, t, ['line_1_size'], 22);
            if (t === 'button') ensureFloor(el.id, t, ['font_size'], FLOOR_BODY);
        });

        

        

        
        
        if (isScreenMode) {
            var MOBILE_BUDGET_PX = 700;     
            var sections = (elements || []).filter(function(e) {
                return (e.type === 'section') && (!e.parent_id || e.parent_id === 0);
            });

            function effective(s, key, fallback) {
                if (s[key + '_mobile'] !== undefined && s[key + '_mobile'] !== '' && s[key + '_mobile'] !== null)
                    return parseInt(s[key + '_mobile']) || 0;
                return parseInt(s[key]) || fallback || 0;
            }

            sections.forEach(function(sec) {
                var sId  = sec.id;
                var sMod = (changes.elements[sId] && changes.elements[sId].mods) || {};
                
                var sMerged = Object.assign({}, sec.settings || {}, sMod);
                var topPad = effective(sMerged, 'padding_top', 60);
                var botPad = effective(sMerged, 'padding_bottom', 60);

                var stack = [sId];
                var contentH = 0;
                while (stack.length) {
                    var pid = stack.pop();
                    (childrenByParent[pid] || []).forEach(function(c) {
                        stack.push(c.id);
                        var cs = Object.assign({}, c.settings || {}, ((changes.elements[c.id] || {}).mods) || {});
                        var t = c.type;
                        if (t === 'title' || t === 'text') {
                            var fs = effective(cs, 'line_1_size', 0) || effective(cs, 'font_size', 0) || effective(cs, 'text_size', 0) || 16;
                            contentH += Math.round(fs * 1.4) + 12;
                        } else if (t === 'icon_card') {
                            var iconRow = (effective(cs, 'icon_size', 32) + effective(cs, 'title_size', 16) + effective(cs, 'text_size', 14) * 2.5);
                            contentH += Math.round(iconRow + 24);
                        } else if (t === 'button') {
                            contentH += 50;
                        } else if (t === 'image' || t === 'video') {
                            contentH += 220;
                        }
                    });
                }

                var totalH = topPad + botPad + contentH;
                if (totalH > MOBILE_BUDGET_PX) {
                    
                    var newTop = Math.max(8,  Math.round(topPad * 0.5));
                    var newBot = Math.max(8,  Math.round(botPad * 0.5));
                    sMod.padding_top_mobile    = newTop;
                    sMod.padding_bottom_mobile = newBot;
                    if (!changes.elements[sId]) {
                        changes.elements[sId] = {
                            type: 'section',
                            name: (sec.settings && (sec.settings.struct_label || sec.settings.label)) || 'section',
                            mods: sMod
                        };
                        totalChanges += 2;
                    } else {
                        
                        if (!('padding_top_mobile' in changes.elements[sId].mods)) totalChanges++;
                        if (!('padding_bottom_mobile' in changes.elements[sId].mods)) totalChanges++;
                        changes.elements[sId].mods.padding_top_mobile    = newTop;
                        changes.elements[sId].mods.padding_bottom_mobile = newBot;
                    }
                }
            });
        }

        changes.totalChanges = totalChanges;
        return changes;
    }
    
    function showMobileOptimizerModal(changes, elements) {
        console.log('[Mobile optimizer] showMobileOptimizerModal called, totalChanges=' + changes.totalChanges);
        $('#impulse-mobile-optimizer-modal').remove();

        if (!document.getElementById('impulse-mo-scrollbar-css')) {
            var _moStyle = document.createElement('style');
            _moStyle.id = 'impulse-mo-scrollbar-css';
            _moStyle.textContent =
                '.impulse-mo-scroll{scrollbar-width:none;-ms-overflow-style:none}'
                + '.impulse-mo-scroll::-webkit-scrollbar{display:none;width:0;height:0}'
                + '.impulse-mo-row{cursor:pointer;transition:opacity .12s}'
                + '.impulse-mo-row:hover{background:rgba(255,255,255,.03)}'
                + '.impulse-mo-row.is-skipped{opacity:.35}'
                + '.impulse-mo-row.is-skipped .impulse-mo-arrow,'
                + '.impulse-mo-row.is-skipped .impulse-mo-new{text-decoration:line-through}';
            document.head.appendChild(_moStyle);
        }

        var html = '<div id="impulse-mobile-optimizer-modal" style="position:fixed;top:0;left:0;right:0;bottom:0;z-index:2000000;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6)">';
        html += '<div style="background:'+ImpC.surface2+';border-radius:8px;width:420px;max-height:70vh;display:flex;flex-direction:column;border:1px solid '+ImpC.border+';box-shadow:0 20px 60px rgba(0,0,0,0.5)">';

        html += '<div style="padding:16px 20px;border-bottom:1px solid '+ImpC.border+';display:flex;align-items:center;justify-content:space-between">';
        html += '<div style="display:flex;align-items:center;gap:8px"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="'+ImpC.text+'" stroke-width="2"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg><span style="font-size:14px;font-weight:600;color:'+ImpC.text+'">Mobile Optimizer</span></div>';
        html += '<button type="button" class="impulse-mo-close" style="background:none;border:none;color:'+ImpC.muted+';cursor:pointer;font-size:18px;padding:0;line-height:1">&times;</button>';
        html += '</div>';

        html += '<div class="impulse-mo-scroll" style="padding:16px 20px;overflow-y:auto;flex:1">';
        
        if (changes.totalChanges === 0) {
            html += '<div style="text-align:center;padding:20px 0;color:#888"><p style="font-size:13px;margin:0">All elements already have mobile overrides.</p><p style="font-size:11px;margin:8px 0 0;color:#666">Nothing to optimize.</p></div>';
        } else {
            html += '<div style="font-size:11px;color:#888;margin-bottom:12px">' + changes.totalChanges + ' mobile override' + (changes.totalChanges !== 1 ? 's' : '') + ' proposed. Desktop values stay untouched.</div>';

            if (Object.keys(changes.page).length) {
                html += '<div style="font-size:10px;color:'+ImpC.dim+';text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px">PAGE SETTINGS</div>';
                var _pagePrev = Impulse.pageSettings || {};
                for (var pk in changes.page) {
                    var _pDevice = /_mobile$/.test(pk) ? 'mobile' : (/_tablet$/.test(pk) ? 'tablet' : 'all');
                    var _pBase = pk.replace(/_mobile$|_tablet$/, '');
                    var _pLabel = _pBase.replace(/_/g, ' ');
                    var _pOld = (_pagePrev[_pBase] !== undefined && _pagePrev[_pBase] !== '') ? _pagePrev[_pBase] : '—';
                    var _pNew = changes.page[pk];
                    if (/^\d+$/.test(String(_pOld)) && /(padding|gap|margin|height|width|size)/i.test(_pBase)) _pOld = _pOld + 'px';
                    if (/^\d+$/.test(String(_pNew)) && /(padding|gap|margin|height|width|size)/i.test(_pBase)) _pNew = _pNew + 'px';
                    var _pBadge = '<span style="display:inline-block;font-size:9px;color:'+ImpC.dim+';background:'+ImpC.panel+';padding:1px 5px;border-radius:2px;margin-left:6px;text-transform:uppercase">' + _pDevice + '</span>';
                    html += '<div class="impulse-mo-row" data-scope="page" data-key="' + escapeHtml(pk) + '" style="display:flex;justify-content:space-between;align-items:center;padding:4px 6px;font-size:11px;border-bottom:1px solid '+ImpC.panel+'" title="Click to skip this change"><span style="color:'+ImpC.muted+'">' + _pLabel + _pBadge + '</span><span style="font-family:ui-monospace,Menlo,monospace;font-size:10px"><span style="color:'+ImpC.dim+';text-decoration:line-through">' + _pOld + '</span> <span class="impulse-mo-arrow" style="color:'+ImpC.dim+';margin:0 4px">→</span> <span class="impulse-mo-new" style="color:'+ImpC.text+'">' + _pNew + '</span></span></div>';
                }
                html += '<div style="height:10px"></div>';
            }

            var _elMap = {};
            (elements || []).forEach(function(e) { _elMap[e.id] = e; });
            function _stripTagsAndTrim(str) {
                return String(str || '').replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
            }
            function _buildElName(type, s) {
                var snip = '';
                if (s.struct_label) snip = s.struct_label;
                else if (s.label) snip = s.label;
                else if (s.la_text) snip = s.la_text;
                else if (s.line_1) snip = s.line_1;
                else if (s.title) snip = s.title;
                else if (s.heading) snip = s.heading;
                else if (s.content) snip = _stripTagsAndTrim(s.content);
                else if (s.text) snip = _stripTagsAndTrim(s.text);
                snip = _stripTagsAndTrim(snip);
                if (!snip) return '';
                if (snip.length > 40) snip = snip.substring(0, 40) + '…';
                return snip;
            }
            function _fmtValue(v, key) {
                if (v === undefined || v === null || v === '') return '—';
                if (typeof v === 'object') return JSON.stringify(v).substring(0, 24);
                var s = String(v);
                
                if (/(size|padding|gap|margin|height|width|radius|thickness|spacing)/i.test(key) && /^\d+$/.test(s)) {
                    return s + 'px';
                }
                return s.length > 24 ? s.substring(0, 24) + '…' : s;
            }

            for (var elId in changes.elements) {
                var ec = changes.elements[elId];
                var srcEl = _elMap[elId] || {};
                var srcSettings = srcEl.settings || {};
                var typeName = (ec.type || '').replace(/_/g, ' ');
                var nameSnip = _buildElName(ec.type, srcSettings);
                var heading = typeName.toUpperCase() + (nameSnip ? ' · ' + escapeHtml(nameSnip) : '') + '  #' + elId;
                html += '<div style="font-size:10px;color:'+ImpC.dim+';text-transform:uppercase;letter-spacing:0.05em;margin-bottom:4px;margin-top:10px">' + heading + '</div>';
                var modCount = 0;
                for (var mk in ec.mods) {
                    var device = /_mobile$/.test(mk) ? 'mobile' : (/_tablet$/.test(mk) ? 'tablet' : 'all');
                    var baseKey = mk.replace(/_mobile$|_tablet$/, '');
                    var label = baseKey.replace(/_/g, ' ');
                    var oldVal = _fmtValue(srcSettings[baseKey], baseKey);
                    var newVal = _fmtValue(ec.mods[mk], baseKey);
                    var deviceBadge = '<span style="display:inline-block;font-size:9px;color:'+ImpC.dim+';background:'+ImpC.panel+';padding:1px 5px;border-radius:2px;margin-left:6px;text-transform:uppercase;letter-spacing:0.03em">' + device + '</span>';
                    html += '<div class="impulse-mo-row" data-scope="el" data-elid="' + escapeHtml(String(elId)) + '" data-key="' + escapeHtml(mk) + '" style="display:flex;justify-content:space-between;align-items:center;padding:4px 6px;font-size:11px;border-bottom:1px solid '+ImpC.panel+'" title="Click to skip this change">';
                    html += '<span style="color:'+ImpC.muted+'">' + label + deviceBadge + '</span>';
                    html += '<span style="color:'+ImpC.text+';font-family:ui-monospace,Menlo,monospace;font-size:10px"><span style="color:'+ImpC.dim+';text-decoration:line-through">' + oldVal + '</span> <span class="impulse-mo-arrow" style="color:'+ImpC.dim+';margin:0 4px">→</span> <span class="impulse-mo-new">' + newVal + '</span></span>';
                    html += '</div>';
                    modCount++;
                    if (modCount >= 12) {
                        var remaining = Object.keys(ec.mods).length - modCount;
                        if (remaining > 0) {
                            html += '<div style="font-size:10px;color:'+ImpC.dim+';padding:3px 0">+ ' + remaining + ' more</div>';
                            break;
                        }
                    }
                }
            }
        }
        
        html += '</div>';

        html += '<div style="padding:12px 20px;border-top:1px solid '+ImpC.border+';display:flex;gap:8px;justify-content:flex-end">';
        html += '<button type="button" class="impulse-mo-close" style="height:26px;padding:0 16px;background:none;border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.muted+';font-size:11px;cursor:pointer">Cancel</button>';
        if (changes.totalChanges > 0) {
            html += '<button type="button" id="impulse-mo-apply" style="height:26px;padding:0 20px;background:'+ImpC.text+';border:none;border-radius:3px;color:'+ImpC.surface2+';font-size:11px;font-weight:600;cursor:pointer">Apply ' + changes.totalChanges + ' Changes</button>';
        }
        html += '</div></div></div>';
        
        $('body').append(html);
        var _moEl = document.getElementById('impulse-mobile-optimizer-modal');
        if (_moEl) {
            var _r = _moEl.getBoundingClientRect();
            var _cs = getComputedStyle(_moEl);
            console.log('[Mobile optimizer] rect w=' + _r.width + ' h=' + _r.height + ' top=' + _r.top + ' left=' + _r.left + ' zIndex=' + _cs.zIndex + ' parent=' + (_moEl.parentElement && _moEl.parentElement.tagName) + ' viewportW=' + window.innerWidth + ' viewportH=' + window.innerHeight);
            
            var _anc = _moEl.parentElement;
            while (_anc && _anc !== document.body) {
                var _acs = getComputedStyle(_anc);
                if (_acs.transform !== 'none' || _acs.filter !== 'none' || _acs.perspective !== 'none' || _acs.willChange.indexOf('transform') !== -1) {
                    console.warn('[Mobile optimizer] ancestor breaks position:fixed — ' + _anc.tagName + '.' + (_anc.className || '(no class)') + ' transform=' + _acs.transform + ' filter=' + _acs.filter);
                }
                _anc = _anc.parentElement;
            }
        } else {
            console.warn('[Mobile optimizer] modal not found in DOM after append');
        }
        $('#impulse-mobile-optimizer-modal').data('changes', changes).data('elements', elements);
        
        $(document).off('click.moClose').on('click.moClose', '.impulse-mo-close', function() { $('#impulse-mobile-optimizer-modal').remove(); $(document).off('click.moClose click.moApply'); });
        $('#impulse-mobile-optimizer-modal').on('click', function(e) { if (e.target === this) { $(this).remove(); $(document).off('click.moClose click.moApply'); } });

        $(document).off('click.moRow').on('click.moRow', '.impulse-mo-row', function() {
            $(this).toggleClass('is-skipped');
            var $modal = $('#impulse-mobile-optimizer-modal');
            var $btn = $modal.find('#impulse-mo-apply');
            var n = $modal.find('.impulse-mo-row').not('.is-skipped').length;
            if ($btn.length) {
                $btn.text('Apply ' + n + ' Change' + (n === 1 ? '' : 's'));
                $btn.prop('disabled', n === 0).css('opacity', n === 0 ? 0.5 : 1);
            }
        });

        $(document).off('click.moApply').on('click.moApply', '#impulse-mo-apply', function() {
            var btn = this;
            btn.disabled = true;
            btn.textContent = 'Applying\u2026';
            
            var $modal = $('#impulse-mobile-optimizer-modal');
            var keepPage = {}, keepEl = {};
            $modal.find('.impulse-mo-row').not('.is-skipped').each(function() {
                var $r = $(this);
                if ($r.attr('data-scope') === 'page') {
                    var k = $r.attr('data-key');
                    if (changes.page && k in changes.page) keepPage[k] = changes.page[k];
                } else if ($r.attr('data-scope') === 'el') {
                    var elId = $r.attr('data-elid');
                    var ek = $r.attr('data-key');
                    if (changes.elements && changes.elements[elId] && ek in changes.elements[elId].mods) {
                        if (!keepEl[elId]) keepEl[elId] = { type: changes.elements[elId].type, mods: {} };
                        keepEl[elId].mods[ek] = changes.elements[elId].mods[ek];
                    }
                }
            });
            var totalKept = Object.keys(keepPage).length;
            for (var _k in keepEl) totalKept += Object.keys(keepEl[_k].mods).length;
            var filtered = { page: keepPage, elements: keepEl, totalChanges: totalKept };
            $(document).off('click.moClose click.moApply click.moRow');
            applyMobileOptimizations(filtered, elements);
        });
    }
    
    function applyMobileOptimizations(changes, elements) {
        var queue = [];
        
        for (var elId in changes.elements) {
            var ec = changes.elements[elId];
            var origEl = null;
            for (var i = 0; i < elements.length; i++) {
                if (String(elements[i].id) === String(elId)) { origEl = elements[i]; break; }
            }
            if (!origEl) continue;
            var merged = $.extend({}, origEl.settings || {}, ec.mods);
            queue.push({ id: elId, settings: merged });
        }
        
        if (Object.keys(changes.page).length) {
            var ps = $.extend({}, Impulse.pageSettings || {}, changes.page);
            Impulse.pageSettings = ps;
            queue.push({ id: 'page', settings: ps });
        }
        
        var done = 0;
        var total = queue.length;
        
        function processNext() {
            if (done >= total) {
                $('#impulse-mobile-optimizer-modal').remove();
                if (typeof showSaveStatus === 'function') showSaveStatus(false);
                else $('#impulse-save-status').removeClass('saving').addClass('saved').text('Saved');

                

                

                
                var mobileBtn = document.querySelector('.impulse-device-tab[data-device="mobile"]');
                if (mobileBtn) mobileBtn.click();
                var iframe = document.getElementById('impulse-iframe');
                if (iframe) {

                    
                    
                    var base = iframe.src.replace(/[?&]t=\d+/, '').replace(/[?&]_optz=\d+/, '');
                    iframe.src = base + (base.indexOf('?') > -1 ? '&' : '?') + '_optz=' + Date.now();
                } else if (typeof refreshPreview === 'function') {
                    refreshPreview();
                }
                return;
            }
            var item = queue[done];
            done++;
            
            if (item.id === 'page') {
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: item.settings }),
                    complete: processNext
                });
            } else {
                $.ajax({
                    url: Impulse.api + 'elements/' + item.id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: item.settings, page_id: Impulse.pageId }),
                    complete: processNext
                });
            }
        }
        
        if (typeof showSaveStatus === 'function') showSaveStatus(true);
        else $('#impulse-save-status').removeClass('saved').addClass('saving').text('Saving...');
        processNext();
    }

    
    
    var selectMode = false;
    
    function updateBulkCount() {
        var $checked = $('#impulse-canvas-grid .impulse-page-card.is-checked:visible');
        var count = $checked.length;
        $('#impulse-bulk-count').text(count + ' selected');
        $('#impulse-bulk-publish, #impulse-bulk-unpublish, #impulse-bulk-trash').prop('disabled', count === 0);
    }
    
    function exitSelectMode() {
        selectMode = false;
        $('#impulse-select-toggle').removeClass('active');
        $('#impulse-bulk-actions').hide();
        $('#impulse-canvas-grid').removeClass('impulse-select-active');
        $('#impulse-canvas-grid .impulse-page-card').removeClass('is-checked');
        updateBulkCount();
    }

    $('#impulse-select-toggle').on('click', function() {
        selectMode = !selectMode;
        $(this).toggleClass('active', selectMode);
        $('#impulse-bulk-actions').toggle(selectMode);
        $('#impulse-canvas-grid').toggleClass('impulse-select-active', selectMode);
        if (!selectMode) {
            $('#impulse-canvas-grid .impulse-page-card').removeClass('is-checked');
        }
        updateBulkCount();
    });

    $(document).on('click', '.impulse-card-check', function(e) {
        e.stopPropagation();
        $(this).closest('.impulse-page-card').toggleClass('is-checked');
        updateBulkCount();
    });

    $('#impulse-select-all').on('click', function() {
        var $visible = $('#impulse-canvas-grid .impulse-page-card:visible');
        var allChecked = $visible.filter('.is-checked').length === $visible.length;
        $visible.toggleClass('is-checked', !allChecked);
        updateBulkCount();
    });

    $('#impulse-bulk-publish').on('click', function() {
        var $cards = $('#impulse-canvas-grid .impulse-page-card.is-checked:visible');
        if ($cards.length === 0) return;
        
        $cards.css('opacity', '0.5');
        var promises = [];
        $cards.each(function() {
            var id = $(this).data('id');
            promises.push($.ajax({
                url: Impulse.api + 'pages/' + id,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ status: 'published' })
            }));
        });
        
        $.when.apply($, promises).always(function() {
            $cards.each(function() {
                $(this).attr('data-status', 'published').css('opacity', '1');
                $(this).find('.impulse-card-status').addClass('is-live');
            });
            updateTabCounts();
            exitSelectMode();
        });
    });

    $('#impulse-bulk-unpublish').on('click', function() {
        var $cards = $('#impulse-canvas-grid .impulse-page-card.is-checked:visible');
        if ($cards.length === 0) return;
        
        $cards.css('opacity', '0.5');
        var promises = [];
        $cards.each(function() {
            var id = $(this).data('id');
            promises.push($.ajax({
                url: Impulse.api + 'pages/' + id,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ status: 'draft' })
            }));
        });
        
        $.when.apply($, promises).always(function() {
            $cards.each(function() {
                $(this).attr('data-status', 'draft').css('opacity', '1');
                $(this).find('.impulse-card-status').removeClass('is-live');
            });
            updateTabCounts();
            exitSelectMode();
        });
    });

    $('#impulse-bulk-trash').on('click', function() {
        var $cards = $('#impulse-canvas-grid .impulse-page-card.is-checked:visible');
        if ($cards.length === 0) return;
        
        showConfirm('Trash Pages', 'Move ' + $cards.length + ' page(s) to trash?', function() {
            $cards.css('opacity', '0.5');
            var promises = [];
            $cards.each(function() {
                var id = $(this).data('id');
                promises.push($.ajax({
                    url: Impulse.api + 'pages/' + id,
                    method: 'DELETE',
                    headers: { 'X-WP-Nonce': Impulse.nonce }
                }));
            });
            
            $.when.apply($, promises).always(function() {
                $cards.fadeOut(200, function() {
                    $(this).remove();
                    updateTabCounts();
                });
                exitSelectMode();
            });
        });
    });

    $('.impulse-canvas-tab').on('click', function() {
        if (selectMode) exitSelectMode();
    });

    (function() {
        var dragging = false, startX, startY, $box, lassoDidSelect = false;
        var $grid = $('#impulse-canvas-grid');

        $grid.on('mousedown', function(e) {
            if (e.button !== 0) return;
            if ($(e.target).closest('.impulse-page-card').length) return;
            e.preventDefault();
            dragging = true;
            lassoDidSelect = false;
            startX = e.clientX;
            startY = e.clientY;
            $box = $('<div class="impulse-selection-box">').appendTo('body');
            $box.css({ left: startX, top: startY, width: 0, height: 0 });
        });

        $(document).on('mousemove.pagesLasso', function(e) {
            if (!dragging) return;
            var x = Math.min(e.clientX, startX);
            var y = Math.min(e.clientY, startY);
            var w = Math.abs(e.clientX - startX);
            var h = Math.abs(e.clientY - startY);
            $box.css({ left: x, top: y, width: w, height: h });
        });

        $(document).on('mouseup.pagesLasso', function(e) {
            if (!dragging) return;
            dragging = false;
            var boxRect = $box[0].getBoundingClientRect();
            $box.remove();
            $box = null;

            if (boxRect.width < 5 && boxRect.height < 5) return;

            if (!selectMode) {
                selectMode = true;
                $('#impulse-select-toggle').addClass('active');
                $('#impulse-bulk-actions').show();
                $grid.addClass('impulse-select-active');
            }

            var matched = 0;
            $grid.find('.impulse-page-card:visible').each(function() {
                var r = this.getBoundingClientRect();
                if (!(r.right < boxRect.left || r.left > boxRect.right ||
                      r.bottom < boxRect.top  || r.top > boxRect.bottom)) {
                    $(this).addClass('is-checked');
                    matched++;
                }
            });
            if (matched > 0) {
                lassoDidSelect = true;
                updateBulkCount();
            }
        });

        $grid.on('click.pagesLassoSuppress', function(e) {
            if (lassoDidSelect) {
                lassoDidSelect = false;
                e.stopImmediatePropagation();
            }
        });
    }());

    
    $(document).on('click', '.impulse-card-status:not(.is-trash)', function(e) {
        e.stopPropagation();
        e.preventDefault();
        e.stopImmediatePropagation();
        var $badge = $(this);
        var $card = $badge.closest('.impulse-page-card');

        

        var id = $card.data('id') || $badge.data('id');
        var current = ($card.attr('data-status') || '').toLowerCase();
        if (current !== 'published' && current !== 'draft') {
            
            current = $badge.hasClass('is-live') ? 'published' : 'draft';
        }
        var newStatus = current === 'published' ? 'draft' : 'published';
        if (!id) {
            if (typeof showImpulseToast === 'function') showImpulseToast('Cannot update — page id missing');
            return;
        }

        $badge.css('opacity', '0.5');

        $.ajax({
            url: Impulse.api + 'pages/' + id,
            method: 'PUT',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            contentType: 'application/json',
            data: JSON.stringify({ status: newStatus }),
            success: function(resp) {

                $card.attr('data-status', newStatus);
                $card.data('status', newStatus);
                $badge.css('opacity', '1');

                if (newStatus === 'published') {
                    $badge.addClass('is-live').attr('title', 'Live - click to unpublish');
                } else {
                    $badge.removeClass('is-live').attr('title', 'Draft - click to publish');
                }

                if (resp.permalink) {
                    $card.attr('data-url', resp.permalink);
                    $card.data('url', resp.permalink);
                }

                if (typeof updateTabCounts === 'function') updateTabCounts();
            },
            error: function(xhr) {
                $badge.css('opacity', '1');
                var msg = 'Could not change status';
                if (xhr && xhr.status === 403) msg = 'Session expired. Reload the page and try again.';
                else if (xhr && xhr.status === 404) msg = 'Page not found.';
                else if (xhr && xhr.status >= 500) msg = 'Server error. Check the error log.';
                else if (xhr && xhr.status === 0) msg = 'Network error. Check your connection.';
                else if (xhr && xhr.responseJSON && xhr.responseJSON.error) msg = xhr.responseJSON.error;
                if (typeof showImpulseToast === 'function') showImpulseToast(msg);
                if (window.console && console.error) console.error('Publish toggle failed', xhr && xhr.status, xhr && xhr.responseText);
            }
        });
    });

    $(document).on('click', '.impulse-status-btn', function() {
        var $btn = $(this);
        var id = $btn.data('id');
        var isLive = $btn.hasClass('is-live');
        var newStatus = isLive ? 'draft' : 'published';
        
        $btn.css('opacity', '0.5');
        
        $.ajax({
            url: Impulse.api + 'pages/' + id,
            method: 'PUT',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            contentType: 'application/json',
            data: JSON.stringify({ status: newStatus }),
            success: function(resp) {
                var $card = $btn.closest('.impulse-page-card');
                $card.attr('data-status', newStatus);
                $btn.css('opacity', '1');
                
                if (newStatus === 'published') {
                    $btn.addClass('is-live');
                } else {
                    $btn.removeClass('is-live');
                }

                if (resp.permalink) {
                    $card.data('url', resp.permalink);
                    $card.find('.impulse-view-btn').attr('href', resp.permalink);
                    $card.find('.impulse-copy-field input').val(resp.permalink);
                }

                updateTabCounts();
            },
            error: function(xhr) {
                $btn.css('opacity', '1');
                console.error('Status update failed:', xhr.responseText);
            }
        });
    });

    $('.impulse-canvas-empty-trash').on('click', function() {
        var $trashedCards = $('.impulse-page-card[data-status="trash"]');
        if ($trashedCards.length === 0) return;
        
        showConfirm('Empty Trash', 'Permanently delete all ' + $trashedCards.length + ' trashed pages? This cannot be undone.', function() {
            $trashedCards.css('opacity', '0.5');
            var remaining = $trashedCards.length;
            var failed = 0;
            
            function onComplete() {
                remaining--;
                if (remaining <= 0) {
                    updateTabCounts();
                    $('.impulse-canvas-empty-trash').hide();
                    if (failed > 0) {
                        console.error(failed + ' pages could not be deleted');
                    }
                }
            }
            
            $trashedCards.each(function() {
                var $card = $(this);
                var id = $card.data('id');
                $.ajax({
                    url: Impulse.api + 'pages/' + id + '/permanent',
                    method: 'DELETE',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    success: function() {
                        $card.fadeOut(200, function() {
                            $(this).remove();
                            onComplete();
                        });
                    },
                    error: function(xhr) {
                        console.error('Delete failed for page ' + id + ':', xhr.responseText);
                        $card.css('opacity', '1');
                        failed++;
                        onComplete();
                    }
                });
            });
        });
    });

    $(document).on('click', '.impulse-page-name .name-text', function() {
        if ($(this).closest('.impulse-page-card').hasClass('is-frontpage')) return;
        var $wrapper = $(this).closest('.impulse-page-name');
        var $text    = $wrapper.find('.name-text');
        var $input   = $wrapper.find('.name-input');
        $text.hide();
        $input.val($text.text()).show().focus().select();
    });

    function commitPageNameEdit($input) {
        var $wrapper = $input.closest('.impulse-page-name');
        var $text    = $wrapper.find('.name-text');
        var id       = $wrapper.data('id');
        var newName  = $input.val().trim() || $text.text();
        $input.hide();
        $text.text(newName).show();
        
        if (Impulse.pages) {
            var _pg = Impulse.pages.find(function(p){ return String(p.id) === String(id); });
            if (_pg) _pg.name = newName;
        }
        
        $wrapper.closest('.impulse-page-card').find('.impulse-page-preview').attr('data-name', newName);

        

        

        
        var newSlug = newName.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');

        $.ajax({
            url: Impulse.api + 'pages/' + id,
            method: 'PUT',
            headers: { 'X-WP-Nonce': Impulse.nonce },
            contentType: 'application/json',
            data: JSON.stringify({ name: newName, slug: newSlug })
        });
    }

    $(document).on('blur', '.impulse-page-name .name-input', function() {
        commitPageNameEdit($(this));
    });

    $(document).on('keydown', '.impulse-page-name .name-input', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            $(this).blur();
        } else if (e.key === 'Escape') {
            var $wrapper = $(this).closest('.impulse-page-name');
            var origName = $wrapper.find('.name-text').text();
            $(this).val(origName).hide();
            $wrapper.find('.name-text').show();
        }
    });
    
    function updateTabCounts() {
        var published = $('#impulse-canvas-grid .impulse-page-card[data-status="published"]').length;
        var draft = $('#impulse-canvas-grid .impulse-page-card[data-status="draft"]').length;
        var trash = $('#impulse-canvas-grid .impulse-page-card[data-status="trash"]').length;
        var all = published + draft;
        
        $('.impulse-canvas-tab[data-filter="all"] .count').text(all);
        $('.impulse-canvas-tab[data-filter="published"] .count').text(published);
        $('.impulse-canvas-tab[data-filter="draft"] .count').text(draft);
        $('.impulse-canvas-tab[data-filter="trash"] .count').text(trash);
    }

    function showConfirm(title, message, onConfirm) {
        var $modal = $('#impulse-confirm-modal');
        $('#impulse-confirm-title').text(title);
        $('#impulse-confirm-message').text(message);
        $modal.css('display', 'flex');

        $modal.data('onConfirm', onConfirm);
    }

    $('#impulse-confirm-ok').on('click', function() {
        var $modal = $('#impulse-confirm-modal');
        var callback = $modal.data('onConfirm');
        $modal.css('display', 'none');
        if (callback) callback();
    });
    
    $('.impulse-confirm-cancel, #impulse-confirm-modal .impulse-modal-close').on('click', function() {
        $('#impulse-confirm-modal').css('display', 'none');
    });

    

    
    
    var chatColorSwatchTimer = null;

    

    

    $(document).on('click', '.impulse-chat-right .impulse-color-swatch, #settings-chat-panel .impulse-color-swatch', function(e) {
        e.stopPropagation();
        e.stopImmediatePropagation();
        var $swatch = $(this);
        console.log('[chat-swatch] clicked', { swatch: $swatch[0], rect: $swatch[0].getBoundingClientRect(), viewport: { w: window.innerWidth, h: window.innerHeight }, name: ($swatch.next('input').attr('name') || $swatch.parent().find('input').attr('name')) });

        if ($swatch.hasClass('disabled')) { console.log('[chat-swatch] disabled, bail'); return; }

        var $row = $swatch.closest('.impulse-color-row');

        
        
        var cachedPickerEl = $row.data('pickerEl');
        var $picker = cachedPickerEl && document.body.contains(cachedPickerEl)
            ? jQuery(cachedPickerEl)
            : $row.find('.impulse-color-picker');

        if (!$picker.length) {
            var $input = $row.find('.impulse-color-text, input[type="hidden"]');
            var value = $input.val() || '#000000';
            if (value.indexOf('#') !== 0) value = '#000000';

            var r = parseInt(value.substr(1,2), 16) || 0;
            var g = parseInt(value.substr(3,2), 16) || 0;
            var b = parseInt(value.substr(5,2), 16) || 0;
            var max = Math.max(r, g, b), min = Math.min(r, g, b);
            var h = 0, s = 0, v = max / 255;
            var d = max - min;
            s = max === 0 ? 0 : d / max;
            if (max !== min) {
                switch (max) {
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }
                h /= 6;
            }
            var hue = Math.round(h * 360);
            var sat = Math.round(s * 100);
            var val = Math.round(v * 100);
            var hueColor = 'hsl('+hue+',100%,50%)';

            var pickerHtml = '<div class="impulse-color-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'" data-alpha="100">';
            pickerHtml += '<div class="impulse-picker-gradient" style="background-color:'+hueColor+'">';
            pickerHtml += '<div class="impulse-picker-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div></div>';
            pickerHtml += '<div class="impulse-picker-sliders"><div class="impulse-picker-slider-row"><div class="impulse-picker-hue"><div class="impulse-picker-thumb" style="left:'+((hue/360)*100)+'%"></div></div></div></div>';
            pickerHtml += '<div class="impulse-picker-tools">';
            pickerHtml += '<div class="impulse-picker-hex"><input type="text" value="'+value+'" placeholder="#000000"></div>';
            pickerHtml += '<button type="button" class="impulse-picker-eyedropper" title="Pick from screen"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z"/></svg></button>';
            pickerHtml += '</div></div>';

            

            
            
            var $row2 = $swatch.closest('.impulse-color-row');
            var rowKey = $row2.find('input[name]').attr('name') || ('chat-' + Date.now());
            var pickerEl = jQuery(pickerHtml).attr('data-picker-row', rowKey)[0];
            document.body.appendChild(pickerEl);

            

            
            $row2.data('pickerEl', pickerEl);
            jQuery(pickerEl).data('row', $row2[0]);
            $picker = jQuery(pickerEl);
        }

        var wasOpen = $picker.hasClass('open');

        
        $('.impulse-color-picker, .impulse-store-picker').removeClass('open dragging-gradient dragging-hue');

        if (wasOpen) return;

        

        

        var swatchRect = $swatch[0].getBoundingClientRect();
        var pickerWidth = 172;
        var pickerHeight = 170;
        var gap = 8;
        var left = swatchRect.left - pickerWidth - gap;
        var top = swatchRect.top - 10;

        
        
        var inBar = $swatch.closest('#impulse-screen-bar').length > 0;
        if (inBar) {
            top = swatchRect.top - pickerHeight - 6;
            left = swatchRect.left;
        }

        if (!inBar && left < 10) {
            left = swatchRect.right + gap;
        }

        if (!inBar && (left + pickerWidth > window.innerWidth - 10)) {
            left = swatchRect.left;
            top = swatchRect.bottom + 6;
        }

        
        if (top + pickerHeight > window.innerHeight - 10) {
            top = swatchRect.bottom - pickerHeight + 10;
        }
        top = Math.max(10, Math.min(top, window.innerHeight - pickerHeight - 10));

        left = Math.max(10, Math.min(left, window.innerWidth - pickerWidth - 10));

        $picker.css({
            position: 'fixed',
            top: top + 'px',
            left: left + 'px',
            width: pickerWidth + 'px',
            maxWidth: 'none',
            zIndex: 1000030
        });

        $picker.addClass('open');
        console.log('[chat-swatch] picker opened at', { top: top, left: left, picker: $picker[0], hasOpen: $picker.hasClass('open'), computed: { opacity: getComputedStyle($picker[0]).opacity, visibility: getComputedStyle($picker[0]).visibility, display: getComputedStyle($picker[0]).display } });
    });

    var chatColorDefaults = {
        'impulse-chat-color_button': '#000000',
        'impulse-chat-color_header': ''+ImpC.surface2+'',
        'impulse-chat-color_header_text': '#ffffff',
        'impulse-chat-color_avatar_circle': '#000000',
        'impulse-chat-color_background': ''+ImpC.light+'',
        'impulse-chat-color_agent_bubble': ''+ImpC.text+'',
        'impulse-chat-color_visitor_bubble': ''+ImpC.border+'',
        'impulse-chat-color_input_bg': '#ffffff',
        'impulse-chat-color_input_field': '#ffffff',
        'impulse-chat-color_input_border': ''+ImpC.text+'',
        'impulse-chat-color_icons': '#6c757d',
        'impulse-chat-color_send_icon': '#000000'
    };

    
    $(document).on('dblclick', '.impulse-chat-right .impulse-color-swatch, #settings-chat-panel .impulse-color-swatch', function(e) {
        e.stopImmediatePropagation();
        e.preventDefault();
        clearTimeout(chatColorSwatchTimer);
        
        var $swatch = $(this);
        var $row = $swatch.closest('.impulse-color-row');
        var $input = $row.find('.impulse-color-text, input[type="hidden"]');
        var inputId = $input.attr('id');
        var defaultColor = chatColorDefaults[inputId] || '#000000';
        
        $swatch.css('--swatch-color', defaultColor);
        $input.val(defaultColor).trigger('input').trigger('change');

        var target = $swatch.data('live-target');
        var cssProp = $swatch.data('live-css');
        if (target && cssProp) {
            $(target).css(cssProp, defaultColor);
        }

        autoSaveAndPreview();
    });

    function chatUpdatePickerColor($picker) {
        var hue = parseInt($picker.data('hue')) || 0;
        var sat = $picker.data('sat') != null ? parseInt($picker.data('sat')) : 100;
        var val = $picker.data('val') != null ? parseInt($picker.data('val')) : 100;
        var alpha = parseInt($picker.data('alpha'));
        if (isNaN(alpha)) alpha = 100;

        var h = hue / 360, s = sat / 100, v = val / 100;
        var r, g, b;
        var i = Math.floor(h * 6);
        var f = h * 6 - i;
        var p = v * (1 - s);
        var q = v * (1 - f * s);
        var t = v * (1 - (1 - f) * s);
        switch (i % 6) {
            case 0: r = v; g = t; b = p; break;
            case 1: r = q; g = v; b = p; break;
            case 2: r = p; g = v; b = t; break;
            case 3: r = p; g = q; b = v; break;
            case 4: r = t; g = p; b = v; break;
            case 5: r = v; g = p; b = q; break;
        }
        r = Math.round(r * 255);
        g = Math.round(g * 255);
        b = Math.round(b * 255);
        
        var hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
        var colorWithAlpha = alpha < 100 ? 'rgba(' + r + ',' + g + ',' + b + ',' + (alpha/100) + ')' : hex;

        $picker.find('.impulse-picker-hex input').val(hex);

        $picker.find('.impulse-picker-gradient').css('background-color', 'hsl(' + hue + ',100%,50%)');

        $picker.find('.impulse-picker-alpha').css('--alpha-gradient', 'linear-gradient(to right, transparent, ' + hex + ')');

        

        
        
        var rowEl = $picker.data('row');
        if (!rowEl) {
            var rowKey = $picker.attr('data-picker-row');
            if (rowKey) {
                var $matchedInput = jQuery('input[name="' + rowKey + '"]');
                rowEl = $matchedInput.closest('.impulse-color-row')[0];
            }
        }
        var $row = rowEl ? jQuery(rowEl) : $picker.closest('.impulse-color-row');
        var $swatch = $row.find('.impulse-color-swatch');
        $swatch.css('--swatch-color', colorWithAlpha);

        
        $swatch.css('background', colorWithAlpha);

        var $input = $row.find('.impulse-color-text, input[type="hidden"]');
        $input.val(hex).trigger('change').trigger('input');
        console.log('[chat-swatch] color applied', { hex: hex, hasRow: !!$row.length, rowKey: $picker.attr('data-picker-row'), inputName: $input.attr('name'), inputCount: $input.length });

        var target = $swatch.data('live-target');
        var cssProp = $swatch.data('live-css');
        var attrProp = $swatch.data('live-attr');
        if (target) {
            if (cssProp) $(target).css(cssProp, colorWithAlpha);
            if (attrProp) $(target).attr(attrProp, colorWithAlpha);
        }
    }

    

    
    $(document).on('mousedown', '.impulse-chat-right .impulse-picker-gradient, #settings-chat-panel .impulse-picker-gradient, .impulse-color-picker[data-picker-row] .impulse-picker-gradient', function(e) {
        e.preventDefault();
        var $gradient = $(this);
        var $picker = $gradient.closest('.impulse-color-picker');
        var $cursor = $gradient.find('.impulse-picker-cursor');
        
        function updateGradient(e) {
            var rect = $gradient[0].getBoundingClientRect();
            var x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
            var y = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
            
            $cursor.css({ left: (x * 100) + '%', top: (y * 100) + '%' });
            $picker.data('sat', Math.round(x * 100));
            $picker.data('val', Math.round((1 - y) * 100));
            chatUpdatePickerColor($picker);
        }
        
        updateGradient(e);
        
        $(document).on('mousemove.chatgradient', updateGradient);
        $(document).on('mouseup.chatgradient', function() {
            $(document).off('.chatgradient');
        });
    });

    $(document).on('mousedown', '.impulse-chat-right .impulse-picker-hue, #settings-chat-panel .impulse-picker-hue, .impulse-color-picker[data-picker-row] .impulse-picker-hue', function(e) {
        e.preventDefault();
        var $hue = $(this);
        var $picker = $hue.closest('.impulse-color-picker');
        var $thumb = $hue.find('.impulse-picker-thumb');
        
        function updateHue(e) {
            var rect = $hue[0].getBoundingClientRect();
            var x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
            
            $thumb.css('left', (x * 100) + '%');
            $picker.data('hue', Math.round(x * 360));
            chatUpdatePickerColor($picker);
        }
        
        updateHue(e);
        
        $(document).on('mousemove.chathue', updateHue);
        $(document).on('mouseup.chathue', function() {
            $(document).off('.chathue');
        });
    });

    $(document).on('mousedown', '.impulse-chat-right .impulse-picker-alpha, #settings-chat-panel .impulse-picker-alpha, .impulse-color-picker[data-picker-row] .impulse-picker-alpha', function(e) {
        e.preventDefault();
        var $alpha = $(this);
        var $picker = $alpha.closest('.impulse-color-picker');
        var $thumb = $alpha.find('.impulse-picker-thumb');
        
        function updateAlpha(e) {
            var rect = $alpha[0].getBoundingClientRect();
            var x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
            
            $thumb.css('left', (x * 100) + '%');
            $picker.data('alpha', Math.round(x * 100));
            chatUpdatePickerColor($picker);
        }
        
        updateAlpha(e);
        
        $(document).on('mousemove.chatalpha', updateAlpha);
        $(document).on('mouseup.chatalpha', function() {
            $(document).off('.chatalpha');
        });
    });

    $(document).on('input', '.impulse-chat-right .impulse-picker-hex input, #settings-chat-panel .impulse-picker-hex input, .impulse-color-picker[data-picker-row] .impulse-picker-hex input', function() {
        var val = $(this).val().trim();
        if (!/^#[0-9A-Fa-f]{6}$/.test(val)) return;
        
        var $picker = $(this).closest('.impulse-color-picker');

        var r = parseInt(val.substr(1,2), 16);
        var g = parseInt(val.substr(3,2), 16);
        var b = parseInt(val.substr(5,2), 16);
        
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h = 0, s = 0, v = max / 255;
        var d = max - min;
        s = max === 0 ? 0 : d / max;
        if (max !== min) {
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }
        
        var hue = Math.round(h * 360);
        var sat = Math.round(s * 100);
        var valV = Math.round(v * 100);
        
        $picker.data('hue', hue).data('sat', sat).data('val', valV);

        
        
        if (parseInt($picker.data('alpha'), 10) === 0) $picker.data('alpha', 100);

        $picker.find('.impulse-picker-gradient').css('background-color', 'hsl(' + hue + ',100%,50%)');
        $picker.find('.impulse-picker-cursor').css({ left: sat + '%', top: (100 - valV) + '%' });
        $picker.find('.impulse-picker-hue .impulse-picker-thumb').css('left', ((hue/360)*100) + '%');
        
        chatUpdatePickerColor($picker);
    });

    $(document).on('click', '.impulse-chat-right .impulse-picker-apply, #settings-chat-panel .impulse-picker-apply, .impulse-color-picker[data-picker-row] .impulse-picker-apply', function(e) {
        e.stopPropagation();
        var $picker = $(this).closest('.impulse-color-picker');
        var $row = $picker.closest('.impulse-color-row');
        var $input = $row.find('.impulse-color-text, input[type="hidden"]');

        $input.trigger('change');

        $picker.removeClass('open dragging-gradient dragging-hue');
    });

    $(document).on('click', '.impulse-chat-right .impulse-picker-reset, #settings-chat-panel .impulse-picker-reset, .impulse-color-picker[data-picker-row] .impulse-picker-reset', function(e) {
        e.stopPropagation();
        var $picker = $(this).closest('.impulse-color-picker');
        var $row = $picker.closest('.impulse-color-row');
        var defaultColor = $picker.find('.impulse-picker-palette').data('default') || '#ffffff';

        var r = parseInt(defaultColor.substr(1,2), 16) || 255;
        var g = parseInt(defaultColor.substr(3,2), 16) || 255;
        var b = parseInt(defaultColor.substr(5,2), 16) || 255;
        
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h = 0, s = 0, v = max / 255;
        var d = max - min;
        s = max === 0 ? 0 : d / max;
        if (max !== min) {
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }
        
        $picker.data('hue', Math.round(h * 360));
        $picker.data('sat', Math.round(s * 100));
        $picker.data('val', Math.round(v * 100));
        $picker.data('alpha', 100);
        
        chatUpdatePickerColor($picker);
    });

    $(document).on('click', '.impulse-chat-right .impulse-picker-eyedropper, #settings-chat-panel .impulse-picker-eyedropper, .impulse-color-picker[data-picker-row] .impulse-picker-eyedropper', function(e) {
        e.stopPropagation();
        var $picker = $(this).closest('.impulse-color-picker');
        
        if ('EyeDropper' in window) {
            var eyeDropper = new EyeDropper();
            eyeDropper.open().then(function(result) {
                var hex = result.sRGBHex;
                $picker.find('.impulse-picker-hex input').val(hex).trigger('input');
            }).catch(function() {});
        }
    });

    
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.impulse-color-picker, .impulse-color-swatch').length) {
            $('.impulse-chat-right .impulse-color-picker, #settings-chat-panel .impulse-color-picker, .impulse-color-picker[data-picker-row]').removeClass('open dragging-gradient dragging-hue');
        }
    });

    $(document).on('paste', '.impulse-picker-hex input', function(e) {
        e.preventDefault();
        var text = (e.originalEvent.clipboardData || window.clipboardData).getData('text');
        if (!text) return;
        text = text.trim();
        if (text.charAt(0) !== '#') text = '#' + text;
        if (/^#[0-9A-Fa-f]{3,8}$/.test(text)) {
            if (text.length === 4) text = '#' + text[1]+text[1] + text[2]+text[2] + text[3]+text[3];
            $(this).val(text).trigger('input');
        }
    });

    

    
    if (Impulse.pageId) {
        initEditor();
        
        var sm = true;
        $('.impulse-canvas').attr('data-screen-mode', sm ? '1' : '0');
        if (typeof window.showPageSettings === 'function') {
            window.showPageSettings();
        }

        
        
        (function() {

            

            function fitOnDirectLoad() {
                var sm2 = Impulse.pageSettings && (true);
                var canvas = document.querySelector('.impulse-canvas');
                var scroll = document.querySelector('.impulse-canvas-scroll');
                if (!canvas || !scroll) return;
                if (!sm2) {
                    canvas.style.transform = '';
                    canvas.style.transformOrigin = '';
                    scroll.style.height = '';
                    return;
                }
                if (typeof window._impulseRecomputeCanvasFit === 'function') {
                    window._impulseRecomputeCanvasFit();
                }
            }
            
            if (!window.fitScreenCanvas) window.fitScreenCanvas = fitOnDirectLoad;
            
            $('#impulse-iframe').on('load.directFit', function() {
                [0, 50, 150, 300, 600, 1200].forEach(function(ms) { setTimeout(fitOnDirectLoad, ms); });
            });
            
            var _dfTimer = null;
            $(window).on('resize.directFit', function() {
                clearTimeout(_dfTimer);
                _dfTimer = setTimeout(fitOnDirectLoad, 150);
            });
            
            [0, 100, 300, 600, 1200, 2000].forEach(function(ms) { setTimeout(fitOnDirectLoad, ms); });
            
            if (window.ResizeObserver) {
                var ro = new ResizeObserver(function() {
                    clearTimeout(_dfTimer);
                    _dfTimer = setTimeout(fitOnDirectLoad, 60);
                });
                setTimeout(function() {
                    var sc = document.querySelector('.impulse-canvas-scroll');
                    var ifr = document.getElementById('impulse-iframe');
                    if (sc) ro.observe(sc);
                    if (ifr) ro.observe(ifr);
                }, 0);
            }
        })();
    }

    setTimeout(function(){

        if (!Impulse.pageId) {

        }
    }, 600);

    

    (function loadPagesForGrid() {
        $.get(Impulse.api + 'pages', { _wpnonce: Impulse.nonce, per_page: 200 }, function(data) {
            var pages = Array.isArray(data) ? data : (data.pages || []);
            pages = pages.filter(function(p) { return p.type !== 'global_header' && p.type !== 'global_footer'; });
            Impulse.pages = pages.map(function(p) {
                return { id: p.id, name: p.name, slug: p.slug, screen_infinite_loop: !!p.screen_infinite_loop, thumbnail: p.thumbnail || '', permalink: p.permalink || '' };
            });
            
            if (pages.length > 0) $('#impulse-canvas-empty').hide();

        });
    })();

    function initEditor() {
        
        if (window.impulseEditorInitialized) return;
        window.impulseEditorInitialized = true;

        window.enqueueSave        = function() { return enqueueSave.apply(this, arguments); };
        window.openSettings       = function() { return openSettings.apply(this, arguments); };
        window.refreshPreview     = function() { return refreshPreview.apply(this, arguments); };
        window.updateStructureTree= function() { return updateStructureTree.apply(this, arguments); };
        window.postToIframe       = function() { return postToIframe.apply(this, arguments); };
        window.escapeHtml         = function(s) { return escapeHtml(s); };
        window.showToast          = function() { return showToast.apply(this, arguments); };

        
        $(document).on('mousedown', 'input[type="color"]', function(e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        });
        $(document).on('click', 'input[type="color"]', function(e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        });

        
        
        var history = [];
        var historyIndex = -1;
        var isUndoRedo = false; 

        

        var maxHistory = 50;
        var _HISTORY_SESSION_KEY = 'impulse-history-' + (window.Impulse && window.Impulse.pageId ? window.Impulse.pageId : 'global');
        var _DELETED_ARCHIVE_KEY = 'impulse-deleted-archive';
        var _DELETED_ARCHIVE_MAX = 50;

        function _persistHistory() {
            try {
                sessionStorage.setItem(_HISTORY_SESSION_KEY, JSON.stringify({
                    h: history, i: historyIndex, t: Date.now()
                }));
            } catch (_) {}
        }

        function _restoreHistory() {
            try {
                var raw = sessionStorage.getItem(_HISTORY_SESSION_KEY);
                if (!raw) return;
                var blob = JSON.parse(raw);
                if (!blob || !Array.isArray(blob.h)) return;

                
                
                history = blob.h;
                historyIndex = typeof blob.i === 'number' ? blob.i : (history.length - 1);
                if (typeof updateUndoRedoButtons === 'function') updateUndoRedoButtons();
            } catch (_) {}
        }

        

        function _archiveDeletion(entryData) {
            try {
                var raw = localStorage.getItem(_DELETED_ARCHIVE_KEY);
                var arr = raw ? JSON.parse(raw) : [];
                if (!Array.isArray(arr)) arr = [];
                arr.unshift({
                    t:     Date.now(),
                    pageId: (window.Impulse && window.Impulse.pageId) || null,
                    data:  entryData
                });
                if (arr.length > _DELETED_ARCHIVE_MAX) arr.length = _DELETED_ARCHIVE_MAX;
                localStorage.setItem(_DELETED_ARCHIVE_KEY, JSON.stringify(arr));
            } catch (_) {  }
        }

        

        
        window.impulseRecover = function(idx) {
            var raw = localStorage.getItem(_DELETED_ARCHIVE_KEY);
            var arr = [];
            try { arr = raw ? JSON.parse(raw) : []; } catch (_) {}
            if (!Array.isArray(arr)) arr = [];
            if (idx === undefined) {
                if (!arr.length) {
                    console.log('[impulseRecover] archive is empty');
                    return [];
                }
                console.log('[impulseRecover] ' + arr.length + ' archived deletions (most-recent first):');
                arr.forEach(function(e, i) {
                    var t = new Date(e.t).toLocaleString();
                    var d = e.data || {};
                    var sub = d.subtree || {};
                    var rootType = sub.type || d.elementType || '?';
                    var rootId   = d.elementId || '?';
                    var nKids    = function _c(n) { var k=(n && n.children) || []; return k.length + k.reduce(function(s,c){return s+_c(c);},0); }(sub);
                    console.log('  [' + i + ']  ' + t + '  ' + rootType + ' #' + rootId + (nKids ? '  (' + nKids + ' descendants)' : '') + (e.pageId ? '  page=' + e.pageId : ''));
                });
                console.log('Call impulseRecover(N) to restore entry N.');
                return arr;
            }
            var entry = arr[idx];
            if (!entry) { console.warn('[impulseRecover] no entry at index', idx); return null; }

            
            
            history.push({ action: 'delete', data: entry.data, t: entry.t });
            historyIndex = history.length - 1;
            _persistHistory();
            updateUndoRedoButtons();
            $('#impulse-undo').click();
            console.log('[impulseRecover] restoring entry', idx, '— watch for the toast');
            return entry;
        };
        window.impulseRecover.clear = function() {
            localStorage.removeItem(_DELETED_ARCHIVE_KEY);
            console.log('[impulseRecover] archive cleared');
        };

        
        
        setTimeout(_restoreHistory, 0);

        
        var _histRecentKey = {};
        function _markHistRecorded(key) {
            _histRecentKey[key] = Date.now();
        }
        function _wasHistRecorded(key, windowMs) {
            var t = _histRecentKey[key];
            return t && (Date.now() - t) < (windowMs || 250);
        }
        var selectedElementId = null;
        var selectedElementType = null;
        var selectedGridParentId = null; 
        var selectedGridCellIndex = null; 
        var skipNextGridCellSelect = false; 
        var selectedCellGridParentId = null; 
        var selectedCellGridCellKey = null; 

        function isPageSettingsMode() {
            
            if ($('.impulse-panel-right').data('element-id')) return false;
            var t = $('#impulse-settings-title').text();
            if (t === 'Page Settings') return true;
            
            var sm = true;
            return !!(sm === '1' || sm === 1 || sm === true);
        }
        function getPageSettingsTitle() {
            return 'Page Settings';
        }

        
        
        var currentDevice = (sessionStorage.getItem('impulseDevice') || 'desktop');
        window.impulseDevice = currentDevice; 

        
        if (currentDevice !== 'desktop') {
            $('.impulse-device-tab').removeClass('active');
            $('.impulse-device-tab[data-device="' + currentDevice + '"]').addClass('active');
            $('.impulse-canvas').attr('data-device', currentDevice);

            

            

            

            

            

            var _devRenderDone = false;
            function _ensureDeviceRender() {
                if (_devRenderDone) return;
                var dev = window.impulseDevice;
                if (!dev || dev === 'desktop') return;
                var ifr = document.getElementById('impulse-iframe');
                if (ifr && ifr.src && ifr.src.indexOf('device=' + dev) !== -1) {
                    _devRenderDone = true; 
                    return;
                }
                _devRenderDone = true;
                if (typeof refreshPreview === 'function') refreshPreview();
            }
            $(document).one('impulse:preview:loaded', _ensureDeviceRender);
            [350, 800, 1500].forEach(function(ms) { setTimeout(_ensureDeviceRender, ms); });
        }

        window.impulseResetEditorState = function() {
            isRefreshing = false;
            pendingRefresh = false;
            isDragActive = false;
            pendingSelectElement = null;
            
            var iframe = document.getElementById('impulse-iframe');
            if (iframe) {
                clearTimeout(window._iframeOpacitySafety);
                iframe.style.transition = 'none';
                iframe.style.opacity = '1';
            }
            
            $('.impulse-canvas').removeClass('drag-over drag-active');
        };

        function postToIframe(message) {
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage(message, '*');
            }
        }

        

        
        $.ajaxPrefilter(function(options) {
            if (!Impulse.pageId || !options.url) return;
            
            if (options.url.indexOf('/elements/') === -1) return;
            if (options.type === 'GET' || options.method === 'GET' || !options.type) {

                var _hasPageId = options.url.indexOf('page_id=') !== -1;
                if (!_hasPageId && options.data) {
                    var _d = typeof options.data === 'string' ? options.data : '';
                    if (typeof options.data === 'object' && options.data !== null) {
                        _hasPageId = options.data.hasOwnProperty('page_id');
                    } else if (_d.indexOf('page_id=') !== -1) {
                        _hasPageId = true;
                    }
                }
                if (!_hasPageId) {
                    var sep = options.url.indexOf('?') === -1 ? '?' : '&';
                    options.url += sep + 'page_id=' + Impulse.pageId;
                }
            } else if (options.contentType && options.contentType.indexOf('application/json') !== -1 && options.data) {
                
                try {
                    var d = typeof options.data === 'string' ? JSON.parse(options.data) : options.data;
                    if (!d.page_id) {
                        d.page_id = Impulse.pageId;
                        options.data = JSON.stringify(d);
                    }
                } catch(e) {}
            }
        });

        function saveToHistory(action, data) {
            if (isUndoRedo) return;
            window._impulsePageEdited = true;   
            
            if (historyIndex < history.length - 1) {
                history = history.slice(0, historyIndex + 1);
            }
            history.push({ action: action, data: data, t: Date.now() });
            if (history.length > maxHistory) {
                history.shift();
            }
            historyIndex = history.length - 1;
            updateUndoRedoButtons();

            

            _persistHistory();
            if (action === 'delete') _archiveDeletion(data);

            var key = action + ':' + (data && (data.elementId || data.sourceId) || '');
            _markHistRecorded(key);
        }

        
        
        window.saveToHistory = saveToHistory;

        

        
        
        $(document).on('ajaxSend', function(_evt, _xhr, opts) {
            if (isUndoRedo) return;
            if (!opts || !opts.url) return;
            var url = opts.url;
            var method = (opts.method || opts.type || 'GET').toUpperCase();

            var mPut = method === 'PUT' && url.match(/\/elements\/(\d+)(?:\?|$)/);
            if (mPut) {
                var elId = parseInt(mPut[1]);
                if (_wasHistRecorded('update:' + elId)) return;       

                
                var panelId = $('.impulse-panel-right').data('element-id');
                if (panelId != elId) return;
                var prev = $.extend(true, {}, $('.impulse-panel-right').data('existing-settings') || {});
                if (!prev || !Object.keys(prev).length) return;
                
                var _newSettings = null;
                try {
                    var _body = typeof opts.data === 'string' ? JSON.parse(opts.data) : opts.data;
                    if (_body && _body.settings) _newSettings = _body.settings;
                } catch (e) {  }
                
                saveToHistory('update', {
                    elementId: elId,
                    oldSettings: prev,
                    newSettings: _newSettings
                });
                return;
            }

            

        });

        function updateUndoRedoButtons() {
            $('#impulse-undo').prop('disabled', historyIndex < 0);
            $('#impulse-redo').prop('disabled', historyIndex >= history.length - 1);
        }

        

        

        

        
        
        function _undoTargetedRefresh(elementId, verb) {
            refreshElement(elementId);
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe && iframe.contentWindow ? iframe.contentDocument : null;
            var el = doc ? doc.querySelector('.impulse-el[data-id="' + elementId + '"]') : null;

            var needReveal = false, label = '';
            if (el) {
                label = (el.getAttribute('data-type') || '').replace(/_/g, ' ').replace(/\b\w/g, function(c){ return c.toUpperCase(); });
                var win = iframe.contentWindow;
                var r = el.getBoundingClientRect();
                var vh = win.innerHeight || 0, vw = win.innerWidth || 0;
                
                var visible = r.bottom > 4 && r.top < vh - 4 && r.right > 4 && r.left < vw - 4;
                needReveal = !visible;
            }
            if (needReveal) { try { scrollToElementInIframe(elementId); } catch(_e) {} }

            
            var flashDelay = needReveal ? 650 : 520;
            setTimeout(function() {
                var d2 = iframe && iframe.contentWindow ? iframe.contentDocument : null;
                var el2 = d2 ? d2.querySelector('.impulse-el[data-id="' + elementId + '"]') : null;
                if (el2) {
                    el2.classList.remove('impulse-undo-flash');
                    void el2.offsetWidth; 
                    el2.classList.add('impulse-undo-flash');
                    setTimeout(function(){ if (el2) el2.classList.remove('impulse-undo-flash'); }, 950);
                }
            }, flashDelay);
            if (typeof showToast === 'function') {
                showToast((verb || 'Reverted') + (label ? ' ' + label : '') + ' change', 'info');
            }
        }

        $('#impulse-undo').on('click', function() {
            if (historyIndex < 0) return;
            var entry = history[historyIndex];
            historyIndex--;
            isUndoRedo = true;
            
            var d = entry.data;
            switch (entry.action) {
                case 'update':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.elementId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: d.oldSettings, page_id: Impulse.pageId }),
                        success: function() {
                            updateUndoRedoButtons();
                            if (selectedElementId == d.elementId) {
                                openSettings(d.elementId, selectedElementType);
                            }

                            
                            _undoTargetedRefresh(d.elementId, 'Reverted');
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;

                case 'page_settings_update':

                    

                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: d.oldSettings }),
                        success: function() {
                            Impulse.pageSettings = JSON.parse(JSON.stringify(d.oldSettings));
                            _lastPersistedPageSettings = JSON.parse(JSON.stringify(d.oldSettings));
                            $('.impulse-panel-right').data('existing-settings', Impulse.pageSettings);
                            if (typeof applyPageSettingsToPreview === 'function') {
                                try { applyPageSettingsToPreview(Impulse.pageSettings); } catch(_e) {}
                            }
                            updateUndoRedoButtons();
                            refreshPreview();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;

                case 'add':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.elementId,
                        method: 'DELETE',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function() {
                            updateUndoRedoButtons();
                            if (selectedElementId == d.elementId) deselectElement();
                            refreshPreview();
                            updateStructureTree();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;
                    
                case 'delete':

                    

                    

                    

                    

                    

                    

                    
                    function _restorePost(payload) {
                        return new Promise(function(resolve, reject) {
                            $.ajax({
                                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                                method: 'POST',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify(payload),
                                success: function(resp) { resolve(resp && resp.id); },
                                error: function(xhr) { reject(xhr); }
                            });
                        });
                    }
                    function _restoreSubtreeSeq(node, parentId, sortOrder, siblingHints) {
                        var payload = {
                            element_type: node.type || node.section_type,
                            parent_id: parentId || null,
                            sort_order: sortOrder || 0,
                            settings: node.settings || {}
                        };
                        if (siblingHints && (siblingHints.prev || siblingHints.next)) {
                            if (siblingHints.prev) {
                                payload.sibling_id = siblingHints.prev;
                                payload.insert_position = 'after';
                            } else {
                                payload.sibling_id = siblingHints.next;
                                payload.insert_position = 'before';
                            }
                        }
                        return _restorePost(payload).then(function(newId) {
                            var children = node.children || [];
                            if (!children.length) return newId;

                            
                            var p = Promise.resolve(0);
                            children.forEach(function(child, idx) {
                                p = p.then(function(prevChildId) {
                                    var hints = prevChildId ? { prev: prevChildId, next: 0 } : null;
                                    var sortIdx = child.sort_order !== undefined ? child.sort_order : idx;
                                    return _restoreSubtreeSeq(child, newId, sortIdx, hints);
                                });
                            });
                            return p.then(function() { return newId; });
                        });
                    }
                    _restoreSubtreeSeq(
                        d.subtree || { type: d.elementType, settings: d.settings, children: [] },
                        d.parentId || null,
                        d.sortOrder || 0,
                        { prev: d.prevSiblingId || 0, next: d.nextSiblingId || 0 }
                    ).then(function(newRootId) {
                        if (newRootId) d.elementId = newRootId;
                        updateUndoRedoButtons();
                        refreshPreview();
                        updateStructureTree();
                        setTimeout(function() { isUndoRedo = false; }, 600);
                    }).catch(function() {
                        isUndoRedo = false;
                        updateUndoRedoButtons();
                        if (typeof showToast === 'function') {
                            showToast('Undo delete failed — please try again or reload the page.', 'error');
                        }
                    });
                    return;
                    
                case 'reorder':
                case 'move':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.sourceId + '/reorder',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({
                            parent_id: d.oldParentId,
                            sort_order: d.oldSortOrder,
                            cell_row: d.oldCellRow,
                            cell_col: d.oldCellCol,

                            
                            
                            page_id: Impulse.pageId
                        }),
                        success: function() {
                            updateUndoRedoButtons();
                            refreshPreview();
                            updateStructureTree();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;
                case 'wrap-selection':

                    
                    
                    (function () {
                        var _ids = (d.ids || []).slice();
                        var _base = parseInt(d.oldSortOrder, 10) || 0;
                        function back(k) {
                            if (k >= _ids.length) {
                                updateUndoRedoButtons();
                                refreshPreview();
                                updateStructureTree();
                                setTimeout(function () { isUndoRedo = false; }, 600);
                                return;
                            }
                            $.ajax({
                                url: Impulse.api + 'elements/' + _ids[k] + '/reorder',
                                method: 'POST',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify({
                                    parent_id: d.oldParentId,
                                    sort_order: _base + k,
                                    cell_row: null,
                                    cell_col: null
                                })
                            }).always(function () { back(k + 1); });
                        }
                        back(0);
                    })();
                    return;
            }
            isUndoRedo = false;
            updateUndoRedoButtons();
        });

        $('#impulse-redo').on('click', function() {
            if (historyIndex >= history.length - 1) return;
            historyIndex++;
            var entry = history[historyIndex];
            isUndoRedo = true;
            
            var d = entry.data;
            switch (entry.action) {
                case 'update':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.elementId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: d.newSettings, page_id: Impulse.pageId }),
                        success: function() {
                            updateUndoRedoButtons();
                            if (selectedElementId == d.elementId) {
                                openSettings(d.elementId, selectedElementType);
                            }
                            
                            _undoTargetedRefresh(d.elementId, 'Reapplied');
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;

                case 'page_settings_update':

                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: d.newSettings }),
                        success: function() {
                            Impulse.pageSettings = JSON.parse(JSON.stringify(d.newSettings));
                            _lastPersistedPageSettings = JSON.parse(JSON.stringify(d.newSettings));
                            $('.impulse-panel-right').data('existing-settings', Impulse.pageSettings);
                            if (typeof applyPageSettingsToPreview === 'function') {
                                try { applyPageSettingsToPreview(Impulse.pageSettings); } catch(_e) {}
                            }
                            updateUndoRedoButtons();
                            refreshPreview();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;

                case 'add':
                    
                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({
                            element_type: d.elementType,
                            parent_id: d.parentId || null,
                            sort_order: d.sortOrder || 0,
                            settings: d.settings || {}
                        }),
                        success: function(resp) {
                            if (resp.id) d.elementId = resp.id;
                            updateUndoRedoButtons();
                            refreshPreview();
                            updateStructureTree();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;
                    
                case 'delete':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.elementId,
                        method: 'DELETE',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function() {
                            updateUndoRedoButtons();
                            if (selectedElementId == d.elementId) deselectElement();
                            refreshPreview();
                            updateStructureTree();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;
                    
                case 'reorder':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.sourceId + '/reorder',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ target_id: d.targetId, position: d.position, page_id: Impulse.pageId }),
                        success: function() {
                            updateUndoRedoButtons();
                            refreshPreview();
                            updateStructureTree();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;
                    
                case 'move':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + d.sourceId + '/move-into',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify((function(){ var b={parent_id:d.targetId,page_id:Impulse.pageId||0}; if(d.gridCellIndex!=null)b.grid_cell_index=d.gridCellIndex; if(d.cellRow!=null)b.cell_row=d.cellRow; if(d.cellCol!=null)b.cell_col=d.cellCol; if(d.slideIndex!=null)b.slide_index=d.slideIndex; return b; })()),
                        success: function() {
                            updateUndoRedoButtons();
                            refreshPreview();
                            updateStructureTree();
                            setTimeout(function() { isUndoRedo = false; }, 600);
                        },
                        error: function() { isUndoRedo = false; updateUndoRedoButtons(); }
                    });
                    return;
            }
            isUndoRedo = false;
            updateUndoRedoButtons();
        });

        function deselectElement() {
            selectedElementId = null;
            selectedElementType = null;
            window.selectedElementId = null;
            window.selectedElementType = null;
            $(document).trigger('impulse:selection:changed', [null, null]);
            selectedGridParentId = null;
            selectedCellGridParentId = null;
            selectedCellGridCellKey = null;
            $('.impulse-panel-right').removeData('element-id').removeData('element-type');
            postToIframe({ type: 'impulse-deselect' });
            showPageSettings();
        }

        function scrollToElementInIframe(id) {
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentWindow) return;
            try {
                var iframeDoc = iframe.contentDocument;
                var el = iframeDoc.querySelector('.impulse-el[data-id="' + id + '"]');
                if (!el) el = iframeDoc.querySelector('[data-element-id="' + id + '"]');
                if (!el) return;

                

                
                var _isClassic = iframeDoc.body.classList.contains('impulse-scroll-classic');
                if ((Impulse.pageSettings && (true)) && iframe.contentWindow.impulseScreenMode) {
                    var wrapper = iframeDoc.querySelector('.impulse-content-wrapper');
                    if (wrapper) {
                        var screens = wrapper.querySelectorAll(':scope > .impulse-el[data-type="section"]');
                        for (var i = 0; i < screens.length; i++) {
                            if (screens[i] === el || screens[i].contains(el)) {
                                $('.impulse-srow').removeClass('active');
                                $('.impulse-srow[data-screen-index="' + i + '"]').addClass('active');
                                if (_isClassic) break;  

                                

                                

                                
                                if (!screens[i].classList.contains('impulse-screen-active')) {
                                    iframe.contentWindow.impulseScreenMode.goToScreen(i);
                                }
                                return;
                            }
                        }
                    }
                }

                

                

                

                
                
                if (el.getAttribute('data-type') === 'section' && !(el.closest && el.closest('[data-type="footer"]'))) {
                    var _sc = el.ownerDocument.body, _sp = el.parentElement, _iw = iframe.contentWindow;
                    while (_sp) {
                        var _ov = _iw.getComputedStyle(_sp).overflowY;
                        if ((_ov === 'auto' || _ov === 'scroll') && _sp.scrollHeight > _sp.clientHeight + 2) { _sc = _sp; break; }
                        _sp = _sp.parentElement;
                    }
                    var _cR = _sc.getBoundingClientRect(), _eR = el.getBoundingClientRect();

                    

                    

                    

                    var _eps = 2;
                    var _vTop = _cR.top, _vBottom = _cR.top + _sc.clientHeight;
                    var _anyVisible = (_eR.bottom > _vTop + _eps) && (_eR.top < _vBottom - _eps);
                    if (!_anyVisible) {
                        var _tgt = _sc.scrollTop + (_eR.top - _vTop) - 24;
                        _sc.scrollTop = Math.max(0, Math.min(_tgt, _sc.scrollHeight - _sc.clientHeight));
                    }
                }
            } catch(e) {}
        }

        function showPageSettings() {
            var settings = Impulse.pageSettings || {};
            var _sm = true;
            var _isScreenMode = _sm === '1' || _sm === 1 || _sm === true;

            if (_isScreenMode) {
                populateEnvPresets(Impulse.pageSettings || {});

                if (!window._basePageEnv) {
                    window._basePageEnv = {};
                    var _envKeys = ['screen_3d_color1','screen_3d_color2','screen_3d_color3','screen_3d_color4',
                        'screen_3d_speed','screen_3d_intensity','screen_mouse_sens_level',
                        'screen_lava_color1','screen_lava_color2','screen_wave_color1','screen_wave_color2'];
                    _envKeys.forEach(function(k) {
                        if ((Impulse.pageSettings || {})[k] !== undefined) window._basePageEnv[k] = Impulse.pageSettings[k];
                    });
                }

                
                
                $('#impulse-screen-bar').hide();
                $('#impulse-screen-sidebar').show();

                
                try {
                    var _scnCollapsed = localStorage.getItem('impulse_scene_panel_collapsed') === '1';
                    $('#impulse-sequence-body').toggle(!_scnCollapsed);
                    $('#impulse-sequence-chevron').css('transform', _scnCollapsed ? 'rotate(-90deg)' : '');
                    $('#impulse-sequence-toggle').attr('title', _scnCollapsed ? 'Click to expand' : 'Click to collapse');
                } catch(_e) {}

                _showCurrentScreenSettings();
                
                var chatGloballyEnabled2 = !(window.Impulse && window.Impulse.chat && window.Impulse.chat.settings && window.Impulse.chat.settings.enabled === '0');
                $('#impulse-mobile-optimize-footer').show();
                if (chatGloballyEnabled2) setTimeout(function() { $('#impulse-chat-toggle-footer').show(); }, 50);
            } else {
                $('#impulse-screen-bar').hide().html('');
                $('#impulse-screen-sidebar').hide();
                
                var device = window.impulseDevice || 'desktop';
                var panelSettings = device !== 'desktop' ? resolveDeviceSettings(settings, device) : settings;
                var html = buildPageSettingsForm(panelSettings);
                $('#impulse-settings-body').html(html);
                $('#impulse-settings-title').text('Page Settings');
                $('#impulse-deselect').hide();
                $('.impulse-panel-right').show().data('mode', 'page').removeData('element-id');
            }

            $('#impulse-mobile-optimize-footer').show();
            var chatVisible = settings.chat_visible === 1 || settings.chat_visible === '1';
            var chatGloballyEnabled = !(window.Impulse && window.Impulse.chat && window.Impulse.chat.settings && window.Impulse.chat.settings.enabled === '0');
            var $footer = $('#impulse-chat-toggle-footer');
            if (chatGloballyEnabled) {
                $footer.show();

                
                $footer.find('input[name="chat_visible"]').prop('checked', !!chatVisible).trigger('change.cbsync');
            } else {
                $footer.hide();
            }
            setTimeout(updateScreenList, 500);
        }

        function _showCurrentScreenSettings(retryCount) {
            try {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) {
                    
                    if (!retryCount || retryCount < 5) {
                        setTimeout(function() { _showCurrentScreenSettings((retryCount || 0) + 1); }, 150);
                    }
                    return;
                }
                var wrapper = iframe.contentDocument.querySelector('.impulse-content-wrapper');
                if (!wrapper) {
                    if (!retryCount || retryCount < 5) {
                        setTimeout(function() { _showCurrentScreenSettings((retryCount || 0) + 1); }, 150);
                    }
                    return;
                }

                

                
                {
                    var _ps = Impulse.pageSettings || {};

                    var html = '<div class="impulse-setting-group">';

                    

                    

                    var _pgRv = _ps.screen_transition || 'z_depth';
                    var _pgRvBtns = [
                        ['z_depth','Depth']
                        
                    ];

                    

                    
                    
                    var _pgClassic = (_ps.body_scroll === 'classic');

                    
                    
                    var _mst = function(on){ return 'height:28px;font-size:11px;font-weight:600;letter-spacing:0.05em;text-transform:uppercase;border-radius:3px;cursor:pointer;box-sizing:border-box;transition:background .15s ease-in-out,color .15s ease-in-out,border-color .15s ease-in-out;border:1px solid ' + (on ? ImpC.text : ImpC.border) + ';background:' + (on ? ImpC.text : ImpC.surface2) + ';color:' + (on ? ImpC.surface2 : ImpC.muted) + ';'; };
                    html += '<div class="impulse-bodyscroll-group" style="margin-bottom:12px">';
                    html += '<div class="impulse-section-divider" style="margin-top:0">Mode</div>';
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:4px">';
                    html += '<button type="button" class="impulse-mode-btn" data-mode="snap" style="' + _mst(!_pgClassic) + '">Cinematic</button>';
                    html += '<button type="button" class="impulse-mode-btn" data-mode="classic" style="' + _mst(_pgClassic) + '">Classic</button>';
                    html += '</div>';
                    html += '<input type="hidden" name="body_scroll" value="' + (_pgClassic ? 'classic' : 'snap') + '" data-impulse-default="snap">';
                    html += '</div>';

                    

                    
                    
                    html += '<div class="impulse-zone-header impulse-env-header" data-zone="hero" style="display:' + (_pgClassic ? 'none' : 'flex') + ';align-items:center;justify-content:space-between;padding:8px 9px;margin:0 0 12px;font-size:12px;font-weight:600;color:' + ImpC.text + ';user-select:none;cursor:pointer;background:' + ImpC.surface2 + ';border-radius:3px;transition:background 0.15s ease-in-out" title="Open the page environment settings"><span>Environment</span><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.6;flex-shrink:0"><polyline points="9 18 15 12 9 6"/></svg></div>';
                    html += '<div class="impulse-reveal-block" style="display:' + (_pgClassic ? 'none' : 'block') + '">';
                    html += '<div class="impulse-section-divider" style="margin-top:0">Reveal Effect</div>';
                    html += '<div class="impulse-reveal-group" data-key="screen_transition" style="margin-bottom:8px">';
                    html += '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin-bottom:6px">';
                    _pgRvBtns.forEach(function(b) {
                        html += '<button type="button" class="impulse-reveal-btn' + (_pgRv === b[0] ? ' active' : '') + '" data-value="' + b[0] + '">' + b[1] + '</button>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="screen_transition" value="' + _pgRv + '">';
                    html += '</div>';
                    var _pgDepthFam = ['z_depth','depth_spring','depth_vortex','depth_zoom'].indexOf(_pgRv) !== -1;
                    html += '<div class="impulse-margin-grid impulse-z-depth-options" style="display:' + (_pgDepthFam ? 'grid' : 'none') + ';margin-bottom:10px">';
                    html += settingSliderR('screen_intensity', 'Depth', _ps, 50, 0, 100, '%');
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-bottom:10px">';
                    html += settingSliderR('screen_speed_display', 'Speed', _ps, 76, 0, 100, '%');
                    html += settingSliderR('screen_mouse_sens_level', 'Sensitivity', _ps, 5, 0, 10, '');
                    html += '</div>';
                    html += '</div>'; 

                    

                    

                    

                    html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:14px">';
                    html += '<span>Background</span>';
                    html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                    html += settingColorSwatchOnly('bg_color', _ps.bg_color || '');
                    html += '</div>';

                    

                    

                    
                    var _poColor1 = _ps.screen_gradient_color1 || 'rgba(0,0,0,0)';
                    var _poColor2 = _ps.screen_gradient_color2 || 'rgba(0,0,0,0)';
                    var _poDiameter, _poRoundness, _poAngle, _poSoftness;
                    if (_ps.screen_gradient_diameter !== undefined) {
                        _poDiameter  = parseInt(_ps.screen_gradient_diameter)  || 100;
                        _poRoundness = parseInt(_ps.screen_gradient_roundness) || 100;
                        _poSoftness  = parseInt(_ps.screen_gradient_softness)  || 100;
                        _poAngle     = _ps.screen_gradient_angle !== undefined ? parseInt(_ps.screen_gradient_angle) : 0;
                    } else {

                        
                        var _legacy = _ps.screen_gradient_shape || '';
                        _poDiameter  = _legacy === 'glow' ? 80 : _legacy === 'linear' ? 200 : _legacy === 'frame' ? 110 : 100;
                        _poRoundness = _legacy === 'linear' ? 0 : _legacy === 'frame' ? 80 : 100;
                        _poSoftness  = _legacy === 'frame' ? 60 : 100;
                        _poAngle     = _ps.screen_gradient_angle !== undefined ? parseInt(_ps.screen_gradient_angle) : 0;
                    }
                    html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:14px">';
                    html += '<span>Overlay</span>';
                    html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                    html += '<div style="display:flex;align-items:center;gap:5px;flex-shrink:0">';
                    html +=     settingColorSwatchOnly('screen_gradient_color1', _poColor1, 'Center color');
                    html +=     settingColorSwap('screen_gradient_color1', 'screen_gradient_color2', 'Swap center ↔ edge');
                    html +=     settingColorSwatchOnly('screen_gradient_color2', _poColor2, 'Edge color');
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSlider('screen_gradient_diameter',  'Diameter',  _poDiameter,  10, 200, '%', true);
                    html += settingSlider('screen_gradient_roundness', 'Roundness', _poRoundness, 0,  100, '%', true);
                    html += settingSlider('screen_gradient_angle',     'Angle',     _poAngle,     0,  360, '°', true);
                    html += settingSlider('screen_gradient_softness',  'Softness',  _poSoftness,  0,  100, '%', true);
                    html += '</div>';

                    
                    
                    html += '<div class="impulse-section-divider" style="margin-top:14px">Padding</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('padding_top',    'Padding Top',    _ps, 0, 0, 200, 'px', true);
                    html += settingSliderR('padding_bottom', 'Padding Bottom', _ps, 0, 0, 200, 'px', true);
                    html += settingSliderR('padding_left',   'Padding Left',   _ps, 0, 0, 200, 'px', true);
                    html += settingSliderR('padding_right',  'Padding Right',  _ps, 0, 0, 200, 'px', true);
                    html += '</div>';

                    

                    html += settingBgShapes(_ps);

                    

                    

                    

                    

                    

                    
                    var _pgLoopRaw = _ps.screen_infinite_loop;
                    var _pgLoopOn = (_pgLoopRaw === undefined || _pgLoopRaw === null || _pgLoopRaw === '')
                        ? true
                        : (_pgLoopRaw === '1' || _pgLoopRaw === 1 || _pgLoopRaw === true);

                    

                    if (!_pgClassic) {
                        html += '<div class="impulse-section-divider" style="margin-top:14px">Page</div>';
                        html += '<label class="impulse-checkbox-row" style="margin-top:6px"><input type="checkbox" name="screen_infinite_loop" value="1"' + (_pgLoopOn ? ' checked' : '') + '><span class="impulse-setting-label">Loop</span></label>';
                    }

                    html += '</div>'; 

                    $('#impulse-settings-body').html(html);
                    upgradeCheckboxes(document.getElementById('impulse-settings-body'));
                    $('#impulse-settings-title').text('Page Settings');
                    $('#impulse-deselect').hide();
                    $('.impulse-panel-right').show().data('mode', 'page').removeData('element-id');
                }
            } catch(e) { console.error('_showCurrentScreenSettings', e); }
        }

        window.showPageSettings = function() { showPageSettings(); };
        window._showCurrentScreenSettings = _showCurrentScreenSettings;

        

        

        

        

        
        function _buildHeroEnvHtml(settings) {
            var Imp = (typeof ImpC !== 'undefined') ? ImpC : { dim:'#999', muted:'#666', border:'#3a3f44', panel:'#1f2227', surface2:'#2a2e33', light:'#f5f5f5', white:'#fff' };
            var cloudEff = settings.screen_cloud_effect || 'none';
            var _3dEffects = ['cosmos','particles','crystal','blob','wormhole','fractal','bubbles','caustics','glass','bubble','fireflies','flow','aurora','aura','topography','plexus','neon','noise','dots','ripple','swirl','kaleidoscope','columns','membrane','nebula','agate','storm','lens','asteroid','grid'];
            var _is3d = _3dEffects.indexOf(cloudEff) !== -1;
            var _isDepth = cloudEff === 'depth_image';
            var _3dK    = function(n) { return 'screen_' + cloudEff + '_color' + n; };
            var _3dSpdK = 'screen_' + cloudEff + '_speed';
            var _3dIntK = 'screen_' + cloudEff + '_intensity';
            var _3dCntK = 'screen_' + cloudEff + '_count';
            var _3dVarK = 'screen_' + cloudEff + '_variation';
            var _3dDenK = 'screen_' + cloudEff + '_density';
            var _3dHaloK = 'screen_' + cloudEff + '_halo';
            var _3dPreK = 'screen_' + cloudEff + '_preset';
            var _3dC1 = settings[_3dK(1)] || '#333333';
            var _3dC2 = settings[_3dK(2)] || '#999999';
            var _3dC3 = settings[_3dK(3)] || '#666666';
            var _3dC4 = settings[_3dK(4)] || '#cccccc';
            var _paletteEffects = ['wave','clouds'];
            var _forceBlackEffects = ['cosmos','caustics','glass','flow','topography','ripple','swirl','kaleidoscope','membrane','neon','bubble','bubbles','aurora','aura','fractal','lava','noise','wormhole','fireflies','columns','nebula','lens','asteroid','particles'];
            var _screenDefaultBg = (cloudEff === 'grid' || _paletteEffects.indexOf(cloudEff) !== -1) ? '#ffffff'
                : (_forceBlackEffects.indexOf(cloudEff) !== -1) ? '#000000' : '#f5f5f5';

            
            
            var _bgLockedEffects = ['glass','clouds','noise'];

            

            var _bgHiddenEffects = ['aurora','aura','bubbles','cosmos','fireflies','swirl','wormhole','lava',
                'caustics','fractal','bubble','flow','topography','neon','ripple','kaleidoscope','noise','blob'];
            
            var _no2Color = ['nebula','noise'];

            
            
            var _no3Color = ['asteroid','bubble','caustics','dots','glass','membrane','storm','agate','neon','ripple','topography','nebula','noise','aurora','aura','fractal','kaleidoscope','swirl','clouds'];
            var _hasPresets = ['lava','wave','particles','crystal','blob','wormhole','fractal','caustics','glass','bubble','fireflies','flow','aura','plexus','topography','neon','noise','dots','ripple','swirl','kaleidoscope','membrane','aurora','clouds','bubbles','columns','nebula','cosmos','asteroid','agate','storm','lens'].indexOf(cloudEff) !== -1;
            var _curPreset = settings[_3dPreK] || '';
            var _depthImg = settings.screen_depth_image || '';
            var _depthMap = settings.screen_depth_map || '';

            

            var _fxOnly2Color = ['fractal','caustics','glass','bubble','topography','neon','noise','dots','ripple','kaleidoscope','membrane','agate','storm','lens'];

            var _showLava = cloudEff === 'lava';
            var _showWave = cloudEff === 'wave';
            var _show3dColors = _is3d && cloudEff !== 'sphere';
            var _hasColors = _showLava || _showWave || _show3dColors;
            var _cn1, _cn2, _cn3, _cn4, _cv1, _cv2, _cv3, _cv4;
            if (_showLava) {
                _cn1 = 'screen_lava_color1'; _cn2 = 'screen_lava_color2'; _cn3 = 'screen_lava_color3'; _cn4 = 'screen_lava_color4';
                _cv1 = settings.screen_lava_color1 || '#333333';
                _cv2 = settings.screen_lava_color2 || '#999999';
                _cv3 = settings.screen_lava_color3 || '#666666';
                _cv4 = settings.screen_lava_color4 || '#cccccc';
            } else if (_showWave) {
                _cn1 = 'screen_wave_color1'; _cn2 = 'screen_wave_color2'; _cn3 = 'screen_wave_color3'; _cn4 = 'screen_wave_color4';
                _cv1 = settings.screen_wave_color1 || '#6b8eff';
                _cv2 = settings.screen_wave_color2 || '#e256a0';
                _cv3 = settings.screen_wave_color3 || '#ff8054';
                _cv4 = settings.screen_wave_color4 || '#9333ea';
            } else {
                _cn1 = _3dK(1); _cn2 = _3dK(2); _cn3 = _3dK(3); _cn4 = _3dK(4);
                _cv1 = _3dC1; _cv2 = _3dC2; _cv3 = _3dC3; _cv4 = _3dC4;
            }

            function envSwatch(name, val, label, dim) {
                return '<div style="display:flex;flex-direction:column;align-items:center;gap:3px;' + (dim || '') + '">'
                    + '<div class="impulse-color-setting impulse-color-swatch-only" data-name="' + name + '" style="display:block;margin:0;width:30px;height:30px">'
                    + '<div class="impulse-color-row" style="height:30px">'
                    + '<div class="impulse-color-swatch" style="--swatch-color:' + (val || '#333333') + ';width:30px;height:30px;min-width:30px;min-height:30px"></div>'
                    + '<input type="hidden" name="' + name + '" value="' + (val || '') + '" class="impulse-color-text">'
                    + '</div></div>'
                    + '<span style="font-size:10px;color:' + Imp.dim + '">' + label + '</span></div>';
            }

            var h = '<div class="impulse-section-divider" style="margin-top:0">Environment</div>';

            var envBtns = [
                ['asteroid','Asteroid'],['aurora','Aurora'],['aura','Aura'],['blob','Blob'],['bubble','Bubble'],['bubbles','Bubbles'],
                ['caustics','Caustics'],['cosmos','Cosmos'],['crystal','Crystal'],
                ['dots','Dots'],['fireflies','Fireflies'],['flow','Flow'],['fractal','Fractal'],['glass','Glass'],['grid','Grid'],
                ['kaleidoscope','Kaleid'],['lava','Lava'],['lens','Lens'],['membrane','Membrane'],
                ['nebula','Nebula'],['neon','Neon'],
                
                ['particles','Particles'],['plexus','Plexus'],
                ['ripple','Ripple'],['storm','Storm'],['swirl','Swirl'],
                ['topography','Topo'],['agate','Agate'],['wave','Wave'],
                ['wormhole','Wormhole'],['columns','Columns'],
                ['depth_image','3D Image']
            ];

            
            
            if (window.isProLocked && window.isProLocked()) {
                h += '<div class="impulse-pro-demo-hint" style="font-size:10px;color:#999;line-height:1.5;margin-bottom:8px;padding:6px 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px">'
                   + '<strong style="color:#e0e0e0;font-weight:600">PRO preview.</strong> Try any 3D background or environment to see how it works. On the free plan the published page shows a flat image. '
                   + '<button type="button" class="impulse-upgrade-link" style="background:transparent;border:none;color:#e0e0e0;font-weight:600;cursor:pointer;padding:0;font:inherit;text-decoration:underline">Go Pro to publish live 3D &rarr;</button>'
                   + '</div>';
            }

            h += '<div class="impulse-effect-presets-wrap impulse-hero-env-grid" style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin-bottom:10px">';
            envBtns.forEach(function(b) {
                var active = (cloudEff === b[0]);
                var proLocked = window.isProEffect && window.isProEffect('environments', b[0]);
                var lockAttrs = proLocked ? ' data-pro-locked="1" data-pro-label="' + b[1] + ' environment"' : '';
                var lockedCls = proLocked ? ' impulse-pro-locked' : '';
                h += '<button type="button" class="impulse-effect-btn' + (active ? ' active' : '') + lockedCls + '" data-value="' + b[0] + '" style="position:relative"' + lockAttrs + '>' + b[1] + '</button>';
            });
            h += '</div>';

            h += '<input type="hidden" name="screen_cloud_effect" value="' + cloudEff + '">';
            h += '<input type="hidden" name="' + _3dPreK + '" value="' + _curPreset + '">';

            if (_isDepth) {

                

                

                
                h += '<div style="display:flex;gap:8px;align-items:flex-end">';
                h += '<div class="impulse-margin-grid" style="flex:1;min-width:0;margin:0">';
                h += settingSliderR('screen_depth_strength', 'Strength', settings, 30, 0, 60, '');
                h += '</div>';
                if (_depthImg) {
                    h += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-depth-change-btn" style="flex:0 0 auto;height:26px;padding:0 10px;font-size:11px;white-space:nowrap">Change image</button>';
                }
                h += '</div>';
                h += '<input type="hidden" name="screen_depth_image" value="' + _depthImg + '">';
                h += '<input type="hidden" name="screen_depth_map" value="' + _depthMap + '">';

                

                

                
                if (_depthImg && !_depthMap) {
                    var _hsDepthAvail = !!(window.Impulse && Impulse.isStandalone);
                    h += '<button type="button" class="impulse-depth-generate-btn" style="width:100%;height:26px;margin-top:6px;background:'+Imp.panel+';border:1px solid '+Imp.border+';border-radius:3px;font-size:11px;color:'+(_hsDepthAvail ? Imp.text : Imp.dim)+';cursor:pointer'+(!_hsDepthAvail ? ';pointer-events:none' : '')+'">Generate Depth</button>';
                }
                h += '<input type="hidden" name="screen_depth_enabled" value="1">';
                h += '<input type="hidden" name="screen_depth_free" value="' + (settings.screen_depth_free || '0') + '">';
            } else if (cloudEff !== 'none' && _hasColors) {
                
                var _bgKey = 'screen_' + cloudEff + '_bg_color';
                var _bgLocked = _bgLockedEffects.indexOf(cloudEff) !== -1;
                var _bSwatchColor = _bgLocked ? _screenDefaultBg : (settings[_bgKey] || settings.bg_color || _screenDefaultBg);
                var _dimBg = _bgLocked ? 'opacity:0.35;pointer-events:none' : '';
                var _dimColors = !_hasColors ? 'opacity:0.35;pointer-events:none' : '';
                var _dimC3 = _fxOnly2Color.indexOf(cloudEff) !== -1 ? 'opacity:0.35;pointer-events:none' : '';

                

                var _fx4Color = ['cosmos','particles','wormhole','bubbles','fireflies','columns'];
                var _is4Color = _fx4Color.indexOf(cloudEff) !== -1;

                
                var _use2Color = (cloudEff === 'plexus' || cloudEff === 'grid');

                h += '<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px">';
                if (cloudEff === 'glass') {

                    

                    var _glassPrismBg = settings.screen_prism_bg || '';
                    var _glassImgVal = settings.screen_depth_image || _glassPrismBg || '';
                    var _glassImgIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>';
                    h += '<div style="display:flex;flex-direction:column;align-items:center;gap:3px">';
                    h += '<div class="impulse-prism-bg-row" style="position:relative">';
                    if (_glassImgVal) {
                        h += '<div style="width:30px;height:30px;border-radius:3px;overflow:hidden;border:1px solid ' + Imp.border + ';cursor:pointer" class="impulse-prism-select-bg" data-tip="Pick 3D image"><img src="' + _glassImgVal + '" style="width:100%;height:100%;object-fit:cover"></div>';
                        h += '<button type="button" class="impulse-prism-remove-bg" data-tip="Remove image" style="position:absolute;top:-4px;right:-4px;width:14px;height:14px;border-radius:50%;background:' + Imp.surface2 + ';border:1px solid ' + Imp.border + ';cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0"><svg viewBox="0 0 24 24" width="8" height="8" xmlns="http://www.w3.org/2000/svg" color="' + Imp.muted + '"><g transform="scale(2.288)" fill="currentColor" stroke="none"><path d="M3.02 0.02l2.23 0c1.44,0 2.75,0.59 3.7,1.54 0.95,0.95 1.54,2.26 1.54,3.7 0,1.44 -0.59,2.75 -1.54,3.7 -0.95,0.95 -2.26,1.54 -3.7,1.54 -1.44,0 -2.75,-0.59 -3.7,-1.54 -0.95,-0.95 -1.54,-2.26 -1.54,-3.7l0 -2.23 2.31 0 0 2.23c0,0.8 0.33,1.53 0.86,2.06 0.53,0.53 1.26,0.86 2.06,0.86 0.8,0 1.53,-0.33 2.06,-0.86 0.53,-0.53 0.86,-1.26 0.86,-2.06 0,-0.8 -0.33,-1.53 -0.86,-2.06 -0.53,-0.53 -1.26,-0.86 -2.06,-0.86l-2.23 0 0 -2.31z"/><rect x="0.02" y="0.02" width="2.31" height="2.31"/></g></svg></button>';
                    } else {
                        h += '<button type="button" class="impulse-prism-select-bg" data-tip="Pick 3D image" style="width:30px;height:30px;background:' + Imp.panel + ';border:1px solid ' + Imp.border + ';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:' + Imp.dim + ';padding:0">' + _glassImgIcon + '</button>';
                    }
                    h += '<input type="hidden" name="screen_prism_bg" value="' + _glassPrismBg + '">';
                    h += '</div>';
                    h += '<span style="font-size:10px;color:' + Imp.dim + '">B</span></div>';
                } else if (_bgHiddenEffects.indexOf(cloudEff) === -1) {
                    h += envSwatch(_bgKey, _bSwatchColor, 'B', _dimBg);
                }
                h += envSwatch(_cn1, _cv1, '1', _dimColors);
                if (_no2Color.indexOf(cloudEff) === -1) h += envSwatch(_cn2, _cv2, '2', _dimColors);
                if (!_use2Color && _no3Color.indexOf(cloudEff) === -1) h += envSwatch(_cn3, _cv3, '3', _dimC3 || _dimColors);
                if (_is4Color) h += envSwatch(_cn4, _cv4, '4', _dimColors);
                h += '</div>';

                
                if (_use2Color || (!_use2Color && _no3Color.indexOf(cloudEff) !== -1)) h += '<input type="hidden" name="' + _cn3 + '" value="' + _cv3 + '" class="impulse-color-text">';
                if (!_is4Color) h += '<input type="hidden" name="' + _cn4 + '" value="' + _cv4 + '" class="impulse-color-text">';

                if (_no2Color.indexOf(cloudEff) !== -1) h += '<input type="hidden" name="' + _cn2 + '" value="' + _cv2 + '" class="impulse-color-text">';
                if (cloudEff !== 'glass' && _bgHiddenEffects.indexOf(cloudEff) !== -1) h += '<input type="hidden" name="' + _bgKey + '" value="' + _bSwatchColor + '" class="impulse-color-text">';

                

                h += '<div class="impulse-margin-grid">';
                if (cloudEff === 'cosmos') {
                    h += settingSliderR(_3dSpdK, 'Speed', settings, 5, 1, 10, '');
                    h += settingSliderR(_3dIntK, 'Nebula', settings, 5, 1, 20, '');
                } else if (_showLava) {
                    h += settingSliderR('screen_lava_speed', 'Speed', settings, 10, 1, 30, '');
                    h += settingSliderR('screen_lava_intensity', 'Intensity', settings, 5, 1, 20, '');
                } else if (_showWave) {
                    h += settingSliderR('screen_wave_speed', 'Speed', settings, 10, 1, 30, '');
                    h += settingSliderR('screen_wave_intensity', 'Intensity', settings, 10, 1, 20, '');
                } else if (cloudEff === 'glass') {
                    var _ovDef = settings.screen_depth_image ? 0 : 100;
                    h += settingSliderR('screen_outer_opacity', 'Overlay', settings, _ovDef, 0, 100, '%');
                    h += settingSliderR(_3dIntK, 'Intensity', settings, 5, 1, 20, '');
                } else if (cloudEff === 'grid') {

                    
                    
                    h += settingSliderR(_3dSpdK, 'Speed', settings, 5, 1, 10, '');
                    h += settingSliderR(_3dIntK, 'Size', settings, 1, 1, 20, '');
                    h += settingSliderR(_3dCntK, 'Count', settings, 7, 1, 24, '');
                    h += settingSliderR(_3dVarK, 'Variation', settings, 3, 0, 10, '');
                    h += settingSliderR(_3dDenK, 'Density', settings, 7, 1, 10, '');
                    h += settingSliderR('screen_mouse_sens_level', 'Mouse', settings, 5, 0, 10, '');
                } else if (cloudEff === 'asteroid') {

                    h += settingSliderR(_3dSpdK, 'Speed', settings, 5, 1, 30, '');
                    h += settingSliderR(_3dIntK, 'Intensity', settings, 5, 1, 20, '');
                    h += settingSliderR(_3dHaloK, 'Halo', settings, 4, 0, 10, '');
                } else {
                    h += settingSliderR(_3dSpdK, 'Speed', settings, 5, 1, (cloudEff === 'storm' ? 10 : 30), '');
                    h += settingSliderR(_3dIntK, 'Intensity', settings, 5, 1, 20, '');
                }

                
                
                if (_hasPresets) {
                    var _glassHasImage = (cloudEff === 'glass' && !!settings.screen_depth_image);
                    var _presetsDim = _glassHasImage ? 'opacity:0.35;pointer-events:none' : '';

                    h += '<div class="impulse-setting-row impulse-preset-cell" style="display:flex;flex-direction:column;align-items:flex-start;gap:4px;' + _presetsDim + '">'
                      +    '<label style="font-size:11px;color:#666;line-height:14px;align-self:flex-start;margin:0">Preset</label>'
                      +    '<div class="impulse-3d-presets-section" style="align-self:flex-start;width:100%;margin:0">'
                      +      '<div class="impulse-3d-presets" style="display:flex;justify-content:flex-start;align-items:flex-start;gap:4px;margin:0;padding:0;width:auto"></div>'
                      +    '</div>'
                      + '</div>';
                }

                
                if (cloudEff !== 'grid') {
                    h += settingSliderR('screen_mouse_sens_level', 'Mouse', settings, 5, 0, 10, '');
                }
                h += '</div>';
            }
            return h;
        }
        window._buildHeroEnvHtml = _buildHeroEnvHtml;

        
        
        function _showZoneSettings(zone) {
            try {
                var _ps = Impulse.pageSettings || {};

                

                
                
                var html = '<div class="impulse-setting-group">';
                html += '<button type="button" class="impulse-zone-back" style="display:flex;align-items:center;gap:5px;background:none;border:none;color:' + ImpC.dim + ';font-size:11px;cursor:pointer;padding:0 0 10px">'
                      + '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>'
                      + 'Page Settings</button>';
                html += _buildHeroEnvHtml(_ps);

                

                
                
                html += '</div>';
                $('#impulse-settings-body').html(html);
                upgradeCheckboxes(document.getElementById('impulse-settings-body'));
                $('#impulse-settings-title').text('Environment');
                $('#impulse-deselect').hide();
                $('.impulse-panel-right').show().data('mode', 'page').removeData('element-id');

                

                
                
                if (typeof window.populateEnvPresets === 'function') {
                    window.populateEnvPresets(_ps);
                }
            } catch(e) { console.error('_showZoneSettings', e); }
        }
        window._showZoneSettings = _showZoneSettings;

        
        
        function populateEnvPresets(settings) {
            window.populateEnvPresets = populateEnvPresets;
            var cloudEff = settings.screen_cloud_effect || 'none';
            var _hasPresets = ['lava','wave','particles','crystal','blob','wormhole','fractal','caustics','glass','bubble','fireflies','flow','aura','plexus','topography','neon','noise','dots','ripple','swirl','kaleidoscope','membrane','aurora','clouds','bubbles','columns','nebula','cosmos','asteroid','agate','storm','lens'].indexOf(cloudEff) !== -1;
            if (!_hasPresets) { $('.impulse-3d-presets').html(''); return; }
            var _3dPreK = 'screen_' + cloudEff + '_preset';
            var _curPreset = settings[_3dPreK] || '';
            var _presetMap = {
                wave:['flow','storm','helix','vortex'],
                particles:['spark','glow','galaxy','prism'],
                crystal:['diamond','amethyst','ruby','emerald'],
                blob:['organic','mercury','plasma','lava_blob'],
                wormhole:['spacetime','void_hole','fire_vortex','ice_vortex'],
                columns:['city','ember','crystal','ocean'],
                caustics:['pool','deep_sea','tropical_c','golden'],
                glass:['crystal','liquid','diamond','cube_g'],
                flow:['ink_flow','lava_f','ocean_f','neon_fl'],
                fireflies:['warm','cool','forest','violet'],
                plexus:['sky','crimson','mint','gold'],
                grid:['gold','mono','blueprint','warm'],
                topography:['terrain_t','ocean_t','volcanic_t','arctic_t'],
                fractal:['classic','fire_f','ice_f','neon_f'],
                ripple:['pond','ocean_rp','mercury_rp','neon_rp'],
                swirl:['vortex','galaxy_sw','fire_sw','ice_sw'],
                nebula:['orion','crab','helix_n','rosette'],
                cosmos:['deep_space','inferno','arctic','galactic'],
                kaleidoscope:['crystal_k','psyche','stained','neon_k'],
                membrane:['tissue','coral','fungal','neon_m'],
                neon:['cyber_n','neon_n','fire_n','ice_n'],
                lava:['volcano','electric','acid','blood'],
                bubble:['ocean','aurora_bu','dusk_bu','fire_bu'],
                noise:['marble','wood','ocean_nf','magma_nf'],
                dots:['ink','neon','violet','fire'],
                aurora:['borealis','twilight_a','polar_a','tropic_a'],
                clouds:['dawn_c','spring_c','dusk_c','ocean_c'],
                aura:['sunset_au','ocean_au','neon_au','forest_au'],
                bubbles:['iridescent','soap','glass_b','neon_b'],
                asteroid:['inner_belt','saturn','kuiper','diamonds'],
                agate:['amethyst','tourmaline','aquamarine','citrine'],
                storm:['sahara','dust_devil','sirocco','haboob'],
                lens:['milky_way','andromeda','deep_field','quasar']
            };
            var _labelMap = {
                wave:['Flow','Storm','Helix','Vortex'],
                particles:['Spark','Nebula','Glow','Galaxy'],
                crystal:['Diamond','Amethyst','Ruby','Emerald'],
                blob:['Organic','Mercury','Plasma','Lava'],
                wormhole:['Spacetime','Void','Fire','Ice'],
                columns:['City','Ember','Crystal','Ocean'],
                caustics:['Pool','Deep Sea','Tropical','Golden'],
                glass:['Crystal','Liquid','Diamond','Cube'],
                flow:['Ink','Sunset','Ocean','Neon'],
                fireflies:['Warm','Cool','Forest','Violet'],
                plexus:['Sky','Crimson','Mint','Gold'],
                grid:['Gold','Mono','Blueprint','Warm'],
                topography:['Terrain','Ocean','Volcanic','Arctic'],
                fractal:['Classic','Fire','Ice','Neon'],
                ripple:['Pond','Ocean','Mercury','Neon'],
                swirl:['Vortex','Galaxy','Fire','Ice'],
                nebula:['Orion','Crab','Helix','Rosette'],
                cosmos:['Deep','Inferno','Arctic','Galactic'],
                kaleidoscope:['Crystal','Psyche','Stained','Neon'],
                membrane:['Tissue','Coral','Fungal','Neon'],
                neon:['Cyber','Neon','Fire','Ice'],
                lava:['Volcano','Electric','Acid','Blood'],
                bubble:['Ocean','Aurora','Dusk','Fire'],
                noise:['Marble','Wood','Ocean','Magma'],
                dots:['Ink','Neon','Violet','Fire'],
                aurora:['Borealis','Twilight','Polar','Tropic'],
                clouds:['Dawn','Spring','Dusk','Ocean'],
                aura:['Sunset','Ocean','Neon','Forest'],
                bubbles:['Iridescent','Soap','Glass','Neon'],
                asteroid:['Inner Belt','Saturn','Kuiper','Diamonds'],
                agate:['Amethyst','Tourmaline','Aquamarine','Citrine'],
                storm:['Sahara','Dust Devil','Sirocco','Haboob'],
                lens:['Milky Way','Andromeda','Deep Field','Quasar']
            };
            var _pn = _presetMap[cloudEff] || [];
            var _labels = _labelMap[cloudEff] || _pn;
            var _isWaveEff = cloudEff === 'wave';
            var _waveCurPreset = $('input[name="screen_wave_preset"]').val() || '';
            var ph = '';
            for (var pi = 0; pi < _pn.length; pi++) {
                var pAct = (_isWaveEff ? _waveCurPreset : _curPreset) === _pn[pi] ? ' active' : '';
                var pClass = _isWaveEff ? 'impulse-wave-preset-btn' : 'impulse-3d-preset-btn';
                ph += '<button type="button" class="' + pClass + pAct + '" data-value="' + _pn[pi] + '" title="' + (_labels[pi]||'') + '" style="width:26px;height:26px;font-size:11px;border:1px solid '+ImpC.border+';background:' + (pAct ? ''+ImpC.white+'' : ''+ImpC.panel+'') + ';color:' + (pAct ? ''+ImpC.surface2+'' : ''+ImpC.muted+'') + ';border-radius:3px;cursor:pointer;flex-shrink:0">' + (pi+1) + '</button>';
            }
            $('.impulse-3d-presets').html(ph);
        }

        

        function buildPageSettingsForm(settings) {

            

            
            
            $('.impulse-panel-right').attr('data-panel-device', window.impulseDevice || 'desktop');
            var html = '';

            html += '<div class="impulse-setting-group">';
            
            var _revealPreset = settings.screen_transition || 'z_depth';
            var _revealBtns = [
                ['z_depth','Depth']
                
            ];
            html += '<div class="impulse-section-divider">Reveal Effects</div>';
            html += '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin-bottom:8px">';
            _revealBtns.forEach(function(b) {
                html += '<button type="button" class="impulse-reveal-btn' + (_revealPreset === b[0] ? ' active' : '') + '" data-value="' + b[0] + '">' + b[1] + '</button>';
            });
            html += '</div>';
            html += '<input type="hidden" name="screen_transition" value="' + _revealPreset + '">';
            var _depthOnR = ['z_depth','depth_spring','depth_vortex','depth_zoom'].indexOf(_revealPreset) !== -1;
            html += '<div class="impulse-margin-grid">';
            html += '<div class="impulse-z-depth-options" style="display:' + (_depthOnR ? 'contents' : 'none') + '">' + settingSliderR('screen_intensity', 'Depth', settings, 50, 0, 100, '%') + '</div>';
            html += settingSliderR('screen_speed_display', 'Speed', settings, 76, 0, 100, '%');
            html += settingSliderR('screen_mouse_sens_level', 'Sensitivity', settings, 5, 0, 10, '');
            html += '</div>';
            
            var _rawLoopR = settings.screen_infinite_loop !== '0' && settings.screen_infinite_loop !== false && settings.screen_infinite_loop !== 0;
            html += '<label class="impulse-checkbox-row" style="margin-top:6px"><input type="checkbox" name="screen_infinite_loop" value="1"' + (_rawLoopR ? ' checked' : '') + '><span class="impulse-setting-label">Loop</span></label>';
            html += '</div>';
            return html;
        }

        

        
        function _impScNoun(form) {
            var classic = !!(window.Impulse && Impulse.pageSettings && Impulse.pageSettings.body_scroll === 'classic');
            if (form === 'PLURAL') return classic ? 'Sections' : 'Screens';
            if (form === 'lower')  return classic ? 'section'  : 'screen';
            return classic ? 'Section' : 'Screen';
        }
        function updateScreenList() {
            var $container = $('#impulse-screen-list');
            if (!$container.length) return;
            try {
                var iframe = document.getElementById('impulse-iframe');
                var iframeDoc = iframe.contentDocument;
                var wrapper = iframeDoc.querySelector('.impulse-content-wrapper');
                var roots = wrapper ? wrapper.querySelectorAll(':scope > .impulse-el[data-type="section"]') : [];
                if (roots.length === 0) { $container.html(''); return; }
                var currentIdx = 0;
                try {
                    if (iframe.contentWindow && iframe.contentWindow.impulseScreenMode && typeof iframe.contentWindow.impulseScreenMode.getCurrentScreen === 'function') {
                        currentIdx = iframe.contentWindow.impulseScreenMode.getCurrentScreen();
                    }
                } catch(e2) {}
                var dupSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="'+ImpC.muted+'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
                var html = '<div class="impulse-screen-list">';
                var screenCount = roots.length;

                
                var heroCount = parseInt((Impulse.pageSettings || {}).hero_screen_count, 10) || 0;
                heroCount = Math.max(0, Math.min(heroCount, screenCount));

                

                

                
                roots.forEach(function(el, idx) {
                    var id = el.getAttribute('data-id') || '';
                    var isHidden = el.hasAttribute('data-hide-desktop');
                    var screenName = el.getAttribute('data-struct-label') || '';
                    if (!screenName) {
                        if (window._impulseScreenNames && window._impulseScreenNames[idx]) {
                            screenName = window._impulseScreenNames[idx];
                        } else {
                            screenName = _impScNoun() + ' ' + (idx + 1);
                        }
                    }
                    var cls = 'impulse-srow' + (isHidden ? ' screen-hidden' : '') + (idx === currentIdx ? ' active' : '');
                    var wasExpanded = !!(window._sceneExpanded && window._sceneExpanded[id]);
                    html += '<div class="' + cls + '" data-id="' + id + '" data-screen-index="' + idx + '" draggable="true">';
                    html += '<div class="impulse-structure-toggle' + (wasExpanded ? ' expanded' : '') + '" title="Expand"><svg viewBox="0 0 24 24" stroke="currentColor" fill="none" stroke-width="2"><polyline points="9 6 15 12 9 18"/></svg></div>';
                    html += '<span class="impulse-srow-name" title="Double-click to rename">' + escapeHtml(screenName) + '</span>';
                    html += '<div class="impulse-srow-actions">';

                    
                    html += '<button type="button" class="impulse-srow-btn" data-action="duplicate" data-id="' + id + '" title="Duplicate ' + _impScNoun('lower') + '">' + dupSvg + '</button>';
                    if (screenCount > 1) {
                        html += '<button type="button" class="impulse-srow-btn" data-action="delete" data-id="' + id + '" title="Remove ' + _impScNoun('lower') + '"><svg viewBox="0 0 24 24" fill="none" stroke="'+ImpC.muted+'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>';
                    }
                    html += '</div></div>';
                });
                html += '</div>';
                $container.html(html);
                $('#impulse-screens-label').text(_impScNoun('PLURAL'));
                $('[id="impulse-add-screen-btn"]').text('+ Add ' + _impScNoun());
                
                var $active = $container.find('.impulse-srow.active');
                var activeId = $active.data('id');
                if (activeId) {
                    $('.impulse-structure-item').removeClass('screen-current');
                    $('.impulse-structure-item[data-id="' + activeId + '"]').addClass('screen-current');
                }
            } catch(e) {}
        }

        
        
        window._sceneExpanded = window._sceneExpanded || {};
        $(document).on('click', '.impulse-srow .impulse-structure-toggle', function(e) {
            e.stopPropagation();
            var $toggle = $(this);
            var $row = $toggle.closest('.impulse-srow');
            var id = $row.data('id');
            if (!id) return;
            var $next = $row.next('.impulse-structure-children[data-scene-row-id="' + id + '"]');
            if ($next.length) {
                $next.remove();
                $toggle.removeClass('expanded');
                delete window._sceneExpanded[id];
                return;
            }
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe && iframe.contentDocument;
            if (!doc || typeof buildStructureItem !== 'function') return;
            var screenEl = doc.querySelector('.impulse-el[data-id="' + id + '"]');
            if (!screenEl) return;
            var $built = buildStructureItem(screenEl, doc);
            var $children = $built.children('.impulse-structure-children');
            if ($children.length && $children.children().length) {
                $children.addClass('expanded').attr('data-scene-row-id', id);
                $row.after($children);
            } else {
                var $empty = $('<div class="impulse-structure-children expanded" data-scene-row-id="' + id + '" style="padding:6px 14px;color:#888;font-size:11px">Empty screen</div>');
                $row.after($empty);
            }
            $toggle.addClass('expanded');
            window._sceneExpanded[id] = true;
        });

        
        
        window._impulseSetSceneDim = function(hidden) {
            hidden = !!hidden;
            if (window._sceneScreensHidden === hidden) return;
            window._sceneScreensHidden = hidden;
            var ifr = document.getElementById('impulse-iframe');
            if (ifr && ifr.contentWindow) {
                ifr.contentWindow.postMessage({ type: 'impulse-scene-screens-dim', hidden: hidden }, '*');
            }
            if (hidden) {
                $('#impulse-scene-hide-screens').text('Show Screens')
                    .css({ background: ImpC.white, color: ImpC.surface2, 'border-color': ImpC.dim });
            } else {
                $('#impulse-scene-hide-screens').text('Hide Screens')
                    .css({ background: ImpC.panel, color: '#888', 'border-color': ImpC.border });
            }
        };
        
        $(document).on('click', '.impulse-srow', function(e) {
            if ($(e.target).closest('.impulse-srow-actions').length) return;
            if ($(e.target).is('input')) return;
            var id = $(this).data('id');
            $(this).addClass('active').siblings().removeClass('active');
            $('.impulse-structure-item').removeClass('screen-current');
            $('.impulse-structure-item[data-id="' + id + '"]').addClass('screen-current');

            var iframe = document.getElementById('impulse-iframe');

            

            
            
            if (iframe) {
                try { if (iframe.getAnimations) iframe.getAnimations().forEach(function(a){ try { a.cancel(); } catch(_e) {} }); } catch(_e) {}
                if (parseFloat(getComputedStyle(iframe).opacity) < 1) {
                    iframe.style.transition = 'none';
                    iframe.style.opacity = '1';
                    iframe.style.pointerEvents = '';
                    void iframe.offsetWidth;
                    iframe.style.transition = 'opacity 0.15s';
                }
            }
            var cw = iframe && iframe.contentWindow;
            var index = parseInt($(this).data('screen-index')) || 0;
            try {
                if (cw && cw.impulseScreenMode) cw.impulseScreenMode.goToScreen(index);
            } catch(e) {}
            window._impulseSetSceneDim(false);
            if (id) {
                selectedElementId = id;
                selectedElementType = 'section';
                openSettings(id, 'section');
            }
        });

        $(document).on('contextmenu', '.impulse-srow', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $row = $(this);
            var id = $row.data('id');
            var idx = parseInt($row.data('screen-index')) || 0;
            if (!id) return;

            var screenCount = $('.impulse-srow').length;
            var isHidden = $row.hasClass('screen-hidden');

            var h = '';
            h += ctxItem('screen-rename', 'Rename');
            h += ctxItem('screen-duplicate', 'Duplicate');
            h += ctxDiv();
            h += ctxItem('screen-toggle-hide', isHidden ? 'Show Screen' : 'Hide Screen');
            h += ctxDiv();
            h += ctxItem('screen-delete', 'Delete', '', screenCount <= 1 ? 'disabled' : 'danger');

            var rect = $row[0].getBoundingClientRect();
            var $m = $('#impulse-context-menu');
            $m.html(h).css({ left: -9999, top: -9999 }).show();
            var mw = $m.outerWidth() || 160;
            var mh = $m.outerHeight() || 120;
            var x = rect.left;
            var y = rect.top - mh - 4;
            if (y < 10) y = rect.bottom + 4;
            if (x + mw > window.innerWidth - 10) x = window.innerWidth - mw - 10;
            $m.css({ left: x, top: y });
            clearTimeout(window._ctxReleaseTimer);
            window._ctxOpen = true;
            window._ctxReleaseTimer = setTimeout(window.ctxHide, 3000);

            window._srowCtxId = id;
            window._srowCtxIdx = idx;
            window._srowCtxRow = $row;
        });

        $(document).on('click', '#impulse-context-menu .impulse-context-item', function() {
            var action = $(this).data('action');
            if (!action || !action.startsWith('screen-')) return;
            var id = window._srowCtxId;
            var idx = window._srowCtxIdx;
            var $row = window._srowCtxRow;
            ctxHide();
            if (!id) return;

            if (action === 'screen-rename') {
                
                var $name = $row.find('.impulse-srow-name');
                if (!$name.find('input').length) $name.trigger('dblclick');

            } else if (action === 'screen-duplicate') {
                if (id) {
                    duplicateElement(id);
                    setTimeout(updateScreenList, 800);
                }

            } else if (action === 'screen-toggle-hide') {
                try {
                    var iframe = document.getElementById('impulse-iframe');
                    var el = iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (el) {
                        var wasHidden = el.hasAttribute('data-hide-desktop');
                        if (wasHidden) {
                            el.removeAttribute('data-hide-desktop');
                        } else {
                            el.setAttribute('data-hide-desktop', '1');
                        }
                        
                        saveStructField(id, { visibility: wasHidden ? 'all' : 'off' });
                    }
                } catch(ex) {}
                setTimeout(updateScreenList, 200);

            } else if (action === 'screen-delete') {
                if ($('.impulse-srow').length <= 1) return;

                

                
                var _descCount = 0;
                try {
                    var _ifrDel = document.getElementById('impulse-iframe');
                    var _scrNode = _ifrDel && _ifrDel.contentDocument && _ifrDel.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (_scrNode) _descCount = _scrNode.querySelectorAll('.impulse-el[data-id]').length;
                } catch(_eDc) {}
                $row.css({ opacity: 0, transform: 'scale(0.98)', transition: 'all 0.2s ease-in-out' });
                setTimeout(function() {
                    deleteElement(id, true);
                    setTimeout(updateScreenList, 600);
                    if (typeof showToast === 'function') {
                        var msg = _descCount > 0
                            ? (_impScNoun() + ' + ' + _descCount + ' child block') + (_descCount === 1 ? '' : 's') + ' deleted. Ctrl+Z to restore.'
                            : (_impScNoun() + ' deleted. Ctrl+Z to restore.');
                        showToast(msg, 'info', 5000);
                    }
                }, 200);
            }
        });

        $(document).on('dblclick', '.impulse-srow-name', function(e) {
            e.stopPropagation();
            var $name = $(this);
            var $row = $name.closest('.impulse-srow');
            if ($name.find('input').length) return;
            var id = $row.data('id');
            var current = $name.text();
            var $input = $('<input type="text" maxlength="40" class="impulse-srow-rename-input" style="width:100%;background:'+ImpC.panel+';border:1px solid '+ImpC.dim+';color:'+ImpC.text+';font-size:11px;padding:1px 4px;border-radius:2px;outline:none;box-sizing:border-box">').val(current);
            $name.empty().append($input);
            $input.focus().select();

            function commit() {
                var val = $input.val().trim();
                var display = val || (_impScNoun() + ' ' + (parseInt($row.data('screen-index')) + 1));
                $name.text(display);
                saveStructField(id, { struct_label: val });
            }
            $input.on('blur', commit);
            $input.on('keydown', function(ev) {
                if (ev.key === 'Enter')  { ev.preventDefault(); $input.trigger('blur'); }
                if (ev.key === 'Escape') { $input.val(current); $input.trigger('blur'); }
            });
        });

        $(document).on('click', '.impulse-srow-btn[data-action="duplicate"]', function(e) {
            e.stopPropagation();
            var id = $(this).data('id') || $(this).closest('.impulse-srow').data('id');
            if (!id) return;

            
            
            duplicateElement(id, function(newId) {
                if (!newId) return;
                $(document).one('impulse:preview:loaded', function() {
                    _navigateToNewScreen(newId);
                });
                
                setTimeout(function() { _navigateToNewScreen(newId); }, 400);
            });
            setTimeout(updateScreenList, 800);
        });

        
        
        function _navigateToNewScreen(newId) {
            try {
                var iframe = document.getElementById('impulse-iframe');
                var doc = iframe && iframe.contentDocument;
                if (!doc) return;
                var secs = Array.prototype.slice.call(doc.querySelectorAll('.impulse-content-wrapper > .impulse-el[data-type="section"]'));
                var idx = -1;
                for (var i = 0; i < secs.length; i++) {
                    if (String(secs[i].getAttribute('data-id')) === String(newId)) { idx = i; break; }
                }
                if (idx < 0) return;
                var cw = iframe.contentWindow;
                if (cw && cw.impulseScreenMode) {
                    if (typeof cw.impulseScreenMode.jumpToScreen === 'function') {
                        cw.impulseScreenMode.jumpToScreen(idx);
                    } else if (typeof cw.impulseScreenMode.goToScreen === 'function') {
                        cw.impulseScreenMode.goToScreen(idx);
                    }
                }
                selectedElementId = newId;
                selectedElementType = 'section';
                openSettings(newId, 'section');
                updateScreenList();
            } catch(e) {}
        }

        $(document).on('click', '.impulse-srow-btn[data-action="goto"]', function(e) {
            e.stopPropagation();
            var index = parseInt($(this).data('screen-index')) || 0;
            var $row = $(this).closest('.impulse-srow');
            var id = $row.data('id');
            $row.addClass('active').siblings().removeClass('active');
            try {
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentWindow && iframe.contentWindow.impulseScreenMode) {
                    iframe.contentWindow.impulseScreenMode.goToScreen(index);
                }
            } catch(ex) {}
            if (id) {
                selectedElementId = id;
                selectedElementType = 'section';
                postToIframe({ type: 'select-element', id: id });
                openSettings(id, 'section');
            }
        });

        $(document).on('click', '.impulse-srow-btn[data-action="delete"]', function(e) {
            e.stopPropagation();
            var id = $(this).data('id');
            var $row = $(this).closest('.impulse-srow');
            $row.css({ opacity: 0, transform: 'scale(0.98)', transition: 'all 0.2s ease-in-out' });
            setTimeout(function() {
                deleteElement(id);
                setTimeout(updateScreenList, 600);
            }, 200);
        });

        (function() {
            var dragId = null;

            

            

            function _moveIframeDom(srcId, targetId, position) {
                try {
                    var iframe = document.getElementById('impulse-iframe');
                    var doc = iframe && iframe.contentDocument;
                    if (!doc) return;
                    var src = doc.querySelector('.impulse-el[data-id="' + srcId + '"]');
                    var tgt = doc.querySelector('.impulse-el[data-id="' + targetId + '"]');
                    if (!src || !tgt || src === tgt) return;
                    if (position === 'before') {
                        tgt.parentNode.insertBefore(src, tgt);
                    } else {
                        tgt.parentNode.insertBefore(src, tgt.nextSibling);
                    }

                    

                    try {
                        var win = iframe.contentWindow;
                        if (win && win.impulseScreenMode && typeof win.impulseScreenMode.refreshOrder === 'function') {
                            win.impulseScreenMode.refreshOrder();
                        }
                    } catch (_eRO) {}
                } catch (_e) {}
            }
            $(document).on('dragstart', '.impulse-srow', function(e) {
                dragId = $(this).data('id');
                $(this).addClass('dragging');

                

                

                

                
                window._impulseSrowDragging = true;

                

                
                
                $('.impulse-structure-children[data-scene-row-id]').each(function() {
                    $(this).attr('data-srow-drag-hidden', '1').css('display', 'none');
                });
                e.originalEvent.dataTransfer.effectAllowed = 'move';

                

                
                
                e.originalEvent.dataTransfer.setData('text/plain', String(dragId));

                

                

                

                window._zoneDividerDragging = false;
            });

            
            
            $(document).on('dragend', '.impulse-zone-divider, .impulse-srow', function() {
                window._zoneDividerDragging = false;
            });
            $(document).on('dragend', '.impulse-srow', function() {
                dragId = null;
                window._impulseSrowDragging = false;
                $('.impulse-srow').removeClass('dragging drag-over-above drag-over-below');

                
                
                $('.impulse-structure-children[data-srow-drag-hidden]').each(function() {
                    $(this).removeAttr('data-srow-drag-hidden').css('display', '');
                });
            });
            $(document).on('dragover', '.impulse-srow', function(e) {
                if (window._zoneDividerDragging) return; 
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                if ($(this).data('id') == dragId) return;
                var rect = this.getBoundingClientRect();
                var isAbove = e.originalEvent.clientY < rect.top + rect.height / 2;
                $('.impulse-srow').removeClass('drag-over-above drag-over-below');
                $(this).addClass(isAbove ? 'drag-over-above' : 'drag-over-below');
            });
            $(document).on('dragleave', '.impulse-srow', function() {
                $(this).removeClass('drag-over-above drag-over-below');
            });

            

            

            

            

            

            
            function _finalZoneAfterDrop(dragId, targetEl, position) {
                var $src      = $('.impulse-srow[data-id="' + dragId + '"]');
                var heroCount = parseInt((Impulse.pageSettings || {}).hero_screen_count, 10) || 0;
                var srcIdx    = parseInt($src.data('screen-index'), 10) || 0;
                var tgtIdx    = parseInt($(targetEl).data('screen-index'), 10) || 0;
                var rawNew    = position === 'before' ? tgtIdx : tgtIdx + 1;

                var newIdx    = (srcIdx < tgtIdx) ? rawNew - 1 : rawNew;
                return newIdx < heroCount ? 'hero' : 'body';
            }

            

            
            
            function _crossZoneNewCount() { return null; }

            
            function _saveHeroCount(n) {
                if (!Impulse.pageSettings) Impulse.pageSettings = {};
                Impulse.pageSettings.hero_screen_count = n;
                if (typeof showSaveStatus === 'function') showSaveStatus(true);
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: Impulse.pageSettings }),
                    success: function() { if (typeof showSaveStatus === 'function') showSaveStatus(); },
                    error:   function() { if (typeof showSaveStatus === 'function') showSaveStatus(); }
                });
            }

            
            
            function _commitScreenMove(srcId, targetId, position, srcZone, destZone) {
                var newCount = _crossZoneNewCount(srcZone, destZone);

                

                
                
                var doReorder = targetId && String(targetId) !== String(srcId);
                if (!doReorder && newCount === null) return; 
                if (newCount !== null) {
                    if (!Impulse.pageSettings) Impulse.pageSettings = {};
                    Impulse.pageSettings.hero_screen_count = newCount; 
                }
                $('.impulse-srow').removeClass('dragging drag-over-above drag-over-below');
                if (doReorder) {
                    _moveIframeDom(srcId, targetId, position);
                    reorderElement(srcId, targetId, position, false, function() {
                        if (newCount !== null) _saveHeroCount(newCount);
                    });
                } else if (newCount !== null) {
                    
                    _saveHeroCount(newCount);
                }
                updateScreenList();
            }
            $(document).on('drop', '.impulse-srow', function(e) {
                if (window._zoneDividerDragging) return;
                e.preventDefault();
                var targetId = $(this).data('id');
                if (!dragId) return;
                if (targetId == dragId) return;
                var rect = this.getBoundingClientRect();
                var position = e.originalEvent.clientY < rect.top + rect.height / 2 ? 'before' : 'after';
                var srcZone  = $('.impulse-srow[data-id="' + dragId + '"]').data('zone');
                var destZone = _finalZoneAfterDrop(dragId, this, position);
                _commitScreenMove(dragId, targetId, position, srcZone, destZone);
            });

            

            

            

            

            $(document).on('dragover', '.impulse-zone-hero', function(e) {
                if (window._zoneDividerDragging) return;
                if (!dragId) return;
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                $(this).addClass('drag-over-below');
            });
            $(document).on('dragleave', '.impulse-zone-hero', function() {
                $(this).removeClass('drag-over-below');
            });
            $(document).on('drop', '.impulse-zone-hero', function(e) {
                if (window._zoneDividerDragging) return;
                if (!dragId) return;
                e.preventDefault();
                $(this).removeClass('drag-over-below');
                
                var rows = document.querySelectorAll('.impulse-srow');
                var heroCount = parseInt((Impulse.pageSettings || {}).hero_screen_count, 10) || 0;
                var targetId = null, position = null;
                if (heroCount > 0 && rows[heroCount - 1]) {
                    targetId = rows[heroCount - 1].getAttribute('data-id'); 
                    position = 'after';
                } else if (rows[0]) {
                    targetId = rows[0].getAttribute('data-id');            
                    position = 'before';
                }
                var srcZone = $('.impulse-srow[data-id="' + dragId + '"]').data('zone');
                
                _commitScreenMove(dragId, targetId, position, srcZone, 'hero');
            });

            

            
            $(document).on('dragover', '.impulse-hero-empty', function(e) {
                if (window._zoneDividerDragging) return;
                if (!dragId) return;
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                this.style.borderColor = ImpC.text;
                this.style.background = ImpC.surface2;
            });
            $(document).on('dragleave', '.impulse-hero-empty', function() {
                this.style.borderColor = ImpC.border;
                this.style.background = '';
            });
            $(document).on('drop', '.impulse-hero-empty', function(e) {
                if (window._zoneDividerDragging) return;
                if (!dragId) return;
                e.preventDefault();
                this.style.borderColor = ImpC.border;
                this.style.background = '';
                var rows = document.querySelectorAll('.impulse-srow');
                var targetId = rows[0] ? rows[0].getAttribute('data-id') : null;
                var srcZone = $('.impulse-srow[data-id="' + dragId + '"]').data('zone');
                _commitScreenMove(dragId, targetId, 'before', srcZone, 'hero');
            });

            

            

            
            
            $(document).on('dragover', '.impulse-zone-divider', function(e) {
                if (window._zoneDividerDragging) return; 
                if (!dragId) return;                     
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                var rect = this.getBoundingClientRect();
                var isAbove = e.originalEvent.clientY < rect.top + rect.height / 2;
                $(this).toggleClass('drag-over-above', isAbove).toggleClass('drag-over-below', !isAbove);
            });
            $(document).on('dragleave', '.impulse-zone-divider', function() {
                $(this).removeClass('drag-over-above drag-over-below');
            });
            $(document).on('drop', '.impulse-zone-divider', function(e) {
                if (window._zoneDividerDragging) return;
                if (!dragId) return;
                e.preventDefault();
                $(this).removeClass('drag-over-above drag-over-below');
                var rect = this.getBoundingClientRect();
                var isAbove = e.originalEvent.clientY < rect.top + rect.height / 2;
                var rows = document.querySelectorAll('.impulse-srow');
                var heroCount = parseInt((Impulse.pageSettings || {}).hero_screen_count, 10) || 0;
                var targetId = null, position = null;
                if (isAbove && heroCount > 0 && rows[heroCount - 1]) {
                    
                    targetId = rows[heroCount - 1].getAttribute('data-id');
                    position = 'after';
                } else if (!isAbove && heroCount < rows.length && rows[heroCount]) {
                    
                    targetId = rows[heroCount].getAttribute('data-id');
                    position = 'before';
                } else if (heroCount === 0 && rows[0]) {
                    targetId = rows[0].getAttribute('data-id');
                    position = 'before';
                } else if (heroCount >= rows.length && rows[rows.length - 1]) {
                    targetId = rows[rows.length - 1].getAttribute('data-id');
                    position = 'after';
                }
                if (targetId && String(targetId) !== String(dragId)) {

                    
                    var srcZone = $('.impulse-srow[data-id="' + dragId + '"]').data('zone');
                    _commitScreenMove(dragId, targetId, position, srcZone, isAbove ? 'hero' : 'body');
                }
            });
        })();

        

        
        (function() {
            var _zoneDrag = false;
            var _zoneHi = null;
            function _clearHi() { if (_zoneHi) { _zoneHi.style.boxShadow = ''; _zoneHi = null; } }
            function _setHeroScreenCount(n) {
                var total = $('.impulse-srow').length;
                n = Math.max(0, Math.min(parseInt(n, 10) || 0, total));
                if (!Impulse.pageSettings) Impulse.pageSettings = {};
                if ((parseInt(Impulse.pageSettings.hero_screen_count, 10) || 0) === n) return;
                Impulse.pageSettings.hero_screen_count = n;
                if (typeof showSaveStatus === 'function') showSaveStatus(true);
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: Impulse.pageSettings }),
                    success: function() { if (typeof showSaveStatus === 'function') showSaveStatus(); },
                    error:   function() { if (typeof showSaveStatus === 'function') showSaveStatus(); }
                });
                updateScreenList();
            }
            $(document).on('dragstart', '.impulse-zone-divider', function(e) {
                _zoneDrag = true;
                window._zoneDividerDragging = true;
                this.style.opacity = '0.45';
                e.originalEvent.dataTransfer.effectAllowed = 'move';
                try { e.originalEvent.dataTransfer.setData('text/plain', 'zone-divider'); } catch(_e) {}
            });
            $(document).on('dragend', '.impulse-zone-divider', function() {
                _zoneDrag = false;
                window._zoneDividerDragging = false;
                this.style.opacity = '';
                _clearHi();
            });
            $(document).on('dragover', '.impulse-srow', function(e) {
                if (!_zoneDrag) return;
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                var rect = this.getBoundingClientRect();
                var above = e.originalEvent.clientY < rect.top + rect.height / 2;
                if (_zoneHi && _zoneHi !== this) _clearHi();
                _zoneHi = this;
                this.style.boxShadow = above
                    ? 'inset 0 2px 0 ' + ImpC.muted
                    : 'inset 0 -2px 0 ' + ImpC.muted;
            });
            $(document).on('drop', '.impulse-srow', function(e) {
                if (!_zoneDrag) return;
                e.preventDefault();
                var idx = parseInt($(this).attr('data-screen-index'), 10) || 0;
                var rect = this.getBoundingClientRect();
                var above = e.originalEvent.clientY < rect.top + rect.height / 2;
                _clearHi();
                _setHeroScreenCount(above ? idx : idx + 1);
            });
        })();

        
        
        $(document).on('click', '.impulse-zone-header', function() {
            var zone = $(this).attr('data-zone');
            if (zone) _showZoneSettings(zone);
        });
        
        $(document).on('click', '.impulse-zone-back', function() {
            if (typeof _showCurrentScreenSettings === 'function') _showCurrentScreenSettings();
        });

        
        function _impulseNavCollectItems() {
            var items = [];
            $('.impulse-nav-items-list .impulse-nav-item-row').each(function() {
                var lbl = $(this).find('.impulse-nav-item-label').val() || '';

                var $sel = $(this).find('.impulse-nav-item-url-select');
                var $txt = $(this).find('.impulse-nav-item-url');
                var url = '';
                if ($sel.length && $sel.is(':visible') && $sel.val() && $sel.val() !== '__custom__') {
                    url = $sel.val();
                } else {
                    url = $txt.val() || '';
                }
                if (lbl === '' && url === '') return; 
                items.push({ label: lbl, url: url });
            });
            $('input[name="items"]').val(JSON.stringify(items));
            autoSaveAndPreview();
        }
        $(document).on('input change', '.impulse-nav-item-label, .impulse-nav-item-url', function() {
            _impulseNavCollectItems();
        });

        

        
        $(document).on('click', '.impulse-nav-item-remove', function() {
            $(this).closest('.impulse-nav-item-row').remove();
            _impulseNavCollectItems();
        });
        $(document).on('click', '.impulse-nav-item-add', function() {
            var $list = $('.impulse-nav-items-list');
            var idx = $list.find('.impulse-nav-item-row').length;

            var inputStyle = 'height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box;outline:none;width:100%;min-width:0';
            var rowHtml =
                '<div class="impulse-nav-item-row" data-index="' + idx + '" draggable="true" style="display:flex;flex-direction:column;gap:5px">' +
                  '<div style="display:grid;grid-template-columns:14px 1fr 26px;gap:5px;align-items:center">' +
                    '<span class="impulse-nav-item-handle" style="flex-shrink:0;cursor:grab;display:flex;align-items:center;color:'+ImpC.dim+'"><svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><circle cx="9" cy="5" r="1.5"/><circle cx="15" cy="5" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/></svg></span>' +
                    '<input type="text" class="impulse-nav-item-label" placeholder="Label" value="" style="' + inputStyle + '">' +
                    '<button type="button" class="impulse-nav-item-remove" title="Remove" style="height:26px;width:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.muted+';cursor:pointer;font-size:14px;line-height:1;padding:0">×</button>' +
                  '</div>' +
                  '<div class="impulse-nav-item-url-cell" style="min-width:0;padding-left:19px">' +
                    '<input type="text" class="impulse-nav-item-url" data-index="' + idx + '" placeholder="Pick a page or type a URL" value="" autocomplete="off" style="' + inputStyle + '">' +
                  '</div>' +
                '</div>';
            $list.append(rowHtml);
            $list.find('.impulse-nav-item-row').last().find('.impulse-nav-item-label').focus();
        });

        
        
        var navDragSrc = null;
        $(document).on('dragstart', '.impulse-nav-item-row', function(e) {
            navDragSrc = this;
            e.originalEvent.dataTransfer.effectAllowed = 'move';
            e.originalEvent.dataTransfer.setData('text/plain', $(this).data('index'));
            $(this).css('opacity', '0.4');
        });
        $(document).on('dragend', '.impulse-nav-item-row', function() {
            $(this).css('opacity', '');
            $('.impulse-nav-item-row').css('border-top', '');
        });
        $(document).on('dragover', '.impulse-nav-item-row', function(e) {
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'move';
            $('.impulse-nav-item-row').css('border-top', '');
            if (this !== navDragSrc) $(this).css('border-top', '2px solid '+ImpC.white+'');
        });
        $(document).on('dragleave', '.impulse-nav-item-row', function() {
            $(this).css('border-top', '');
        });
        $(document).on('drop', '.impulse-nav-item-row', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if (this === navDragSrc) return;
            var $list = $(this).closest('.impulse-nav-items-list');
            var fromIdx = $list.find('.impulse-nav-item-row').index(navDragSrc);
            var toIdx   = $list.find('.impulse-nav-item-row').index(this);
            if (fromIdx === toIdx) return;

            
            if (fromIdx < toIdx) {
                $(navDragSrc).insertAfter(this);
            } else {
                $(navDragSrc).insertBefore(this);
            }
            
            $list.find('.impulse-nav-item-row').each(function(i) { $(this).attr('data-index', i); });
            _impulseNavCollectItems();
        });

        

        

        function _navClosePopup() {
            if (window._navUrlPopup) {
                window._navUrlPopup.remove();
                window._navUrlPopup = null;
            }
        }
        function _navOpenPopup($input) {
            _navClosePopup();
            var pagePicks = [];
            try { pagePicks = JSON.parse($('#impulse-nav-pagepicks-cache').val() || '[]'); } catch (_e) {}
            if (!pagePicks.length) return;
            var $cell = $input.parent();
            $cell.css('position', 'relative');
            var curVal = String($input.val() || '').toLowerCase();

            
            var $popup = $('<div class="impulse-nav-url-popup"></div>').css({
                position: 'absolute',
                top: '100%',
                right: 0,
                left: 0,
                marginTop: '2px',
                maxHeight: '240px',
                maxWidth: '100%',
                overflowY: 'auto',
                overflowX: 'hidden',
                background: ImpC.panel,
                border: '1px solid ' + ImpC.border,
                borderRadius: '3px',
                zIndex: 100,
                fontSize: '11px',
                boxSizing: 'border-box',
                boxShadow: '0 4px 12px rgba(0,0,0,0.4)'
            });
            pagePicks.forEach(function(p) {

                if (curVal && p.url.toLowerCase().indexOf(curVal) < 0
                          && p.name.toLowerCase().indexOf(curVal) < 0) return;
                var $opt = $('<div></div>').css({
                    padding: '6px 8px',
                    cursor: 'pointer',
                    color: ImpC.text,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    display: 'flex',
                    justifyContent: 'space-between',
                    gap: '8px'
                }).append($('<span></span>').text(p.name).css('flex', '1 1 auto'),
                          $('<span></span>').text(p.url).css({ color: ImpC.dim, flex: '0 0 auto' }))
                  .on('mouseenter', function() { $(this).css('background', ImpC.surface2 || '#2a2e33'); })
                  .on('mouseleave', function() { $(this).css('background', 'transparent'); })
                  .on('mousedown', function(e) {
                      e.preventDefault(); 
                      $input.val(p.url).trigger('input').trigger('change');
                      _navClosePopup();
                      $input.focus();
                  });
                $popup.append($opt);
            });
            if (!$popup.children().length) return;
            $cell.append($popup);
            window._navUrlPopup = $popup;
        }
        $(document).on('focus click', '.impulse-nav-item-url', function() {
            _navOpenPopup($(this));
        });
        $(document).on('input', '.impulse-nav-item-url', function() {
            _navOpenPopup($(this)); 
        });

        $(document).on('click', function(e) {
            if (!window._navUrlPopup) return;
            if ($(e.target).closest('.impulse-nav-item-url, .impulse-nav-url-popup').length) return;
            _navClosePopup();
        });
        
        $(document).on('blur', '.impulse-nav-item-url', function() {
            setTimeout(_navClosePopup, 150);
        });

        

        
        
        $(document).on('click', '.impulse-fold-head', function() {
            var key = $(this).data('fold');
            var $body = $(this).next('.impulse-fold-body');
            if (!$body.length) $body = $(this).nextAll('.impulse-fold-body[data-fold-body="' + key + '"]').first();
            var open = $body.is(':visible');
            $body.toggle(!open);
            $(this).find('svg').css('transform', open ? 'rotate(-90deg)' : 'rotate(0deg)');
            try { localStorage.setItem('impulse_fold_' + key, open ? '0' : '1'); } catch (e) {}
        });
        $(document).on('click', '.impulse-reveal-btn', function() {

            if ($(this).closest('.impulse-bodyscroll-group').length) return;

            
            var $grp = $(this).closest('.impulse-reveal-group');
            var $scope = $grp.length ? $grp : $(this).closest('.impulse-panel-right, #impulse-screen-bar');
            $scope.find('.impulse-reveal-btn').removeClass('active');
            $(this).addClass('active');
            var val = $(this).data('value');
            var $inp = $grp.length ? $grp.find('input[type="hidden"]').first() : $scope.find('input[name="screen_transition"]');
            var key = $inp.attr('name') || 'screen_transition';
            if ($inp.length) { $inp.val(val); }
            else if (Impulse.pageSettings) { Impulse.pageSettings[key] = val; }
            var isDepth = ['z_depth','depth_spring','depth_vortex','depth_zoom'].indexOf(val) !== -1;
            var $depthOpts = $grp.length ? $grp.closest('.impulse-setting-group').find('.impulse-z-depth-options') : $scope.find('.impulse-z-depth-options');
            $depthOpts.css('display', isDepth ? 'contents' : 'none');

            
            var ifrm = document.getElementById('impulse-iframe');
            if (ifrm && ifrm.contentDocument && ifrm.contentDocument.body) {
                var _ifb = ifrm.contentDocument.body;
                var _ifw = ifrm.contentDocument.querySelector('.impulse-screen-wrapper');
                if (key === 'hero_transition') {
                    _ifb.dataset.screenHeroTransition = val;
                    if (_ifw) _ifw.dataset.heroTransition = val;
                } else {
                    _ifb.dataset.screenTransition = val;
                    if (_ifw) _ifw.dataset.transition = val;
                }
            }
            if (key === 'screen_transition' && ifrm && ifrm.contentWindow && ifrm.contentWindow.ImpulseScreens && ifrm.contentWindow.ImpulseScreens.updateSettings) {
                ifrm.contentWindow.ImpulseScreens.updateSettings(val);
            }
            autoSavePageSettings(false);
        });

        

        

        $(document).on('click', '.impulse-mode-btn', function() {
            var val = $(this).attr('data-mode'); 
            var cur = (Impulse.pageSettings && Impulse.pageSettings.body_scroll === 'classic') ? 'classic' : 'snap';
            if (cur === val) return; 
            var C = (typeof ImpC !== 'undefined') ? ImpC : { text:'#e0e0e0', border:'#3a3f44', surface2:'#1d2327', muted:'#999' };
            var $grp = $(this).closest('.impulse-bodyscroll-group');
            var classic = (val === 'classic');
            $grp.find('.impulse-mode-btn').each(function() {
                var on = (this.getAttribute('data-mode') === val);
                this.style.borderColor = on ? C.text : C.border;
                this.style.background  = on ? C.text : C.surface2;
                this.style.color       = on ? C.surface2 : C.muted;
            });
            $grp.find('input[name="body_scroll"]').val(val);
            if (Impulse.pageSettings) Impulse.pageSettings.body_scroll = val;
            $grp.closest('.impulse-setting-group').find('.impulse-reveal-block').css('display', classic ? 'none' : 'block');
            $grp.closest('.impulse-setting-group').find('.impulse-env-header').css('display', classic ? 'none' : 'flex'); 
            autoSavePageSettings(true);
            if (typeof updateScreenList === 'function') updateScreenList();
        });

        

        $(document).on('input', 'input[name="screen_min_height_vh"]', function() {
            var v = parseInt(this.value, 10) || 0;
            var ifr = document.getElementById('impulse-iframe');
            var d = ifr && ifr.contentDocument;
            if (!d) return;
            var sel = d.querySelector('.impulse-el[data-type="section"].selected');
            if (sel) {
                if (v > 0) sel.setAttribute('data-native-min-vh', v);
                else sel.removeAttribute('data-native-min-vh');
            }
            if (d.defaultView && typeof d.defaultView._impulseApplyNativeHeights === 'function') {
                d.defaultView._impulseApplyNativeHeights();
            }
        });

        

        $(document).on('click', '#impulse-tl-toggle', function(e) {
            e.preventDefault(); e.stopPropagation();
            var $btn = $(this);
            var $tlPanel = $('.impulse-screen-bar-panel[data-tab="timeline"]');
            var on = !$btn.hasClass('on');
            $btn.toggleClass('on', on);
            if (on) {
                $tlPanel.css('display', 'flex');
                if (window.ImpulseTimelineEditor && typeof window.ImpulseTimelineEditor.render === 'function') {
                    window.ImpulseTimelineEditor.render();
                }
            } else {
                $tlPanel.css('display', 'none');
            }
        });

        

        var _d3InlineCache = null;
        function _load3dInlinePicker() {
            var $wrap = $('.impulse-3d-presets-wrap');
            if (!$wrap.length) return;
            if (_d3InlineCache) { _render3dInline(_d3InlineCache); return; }
            $wrap.html('<div style="color:'+ImpC.dim+';font-size:11px;padding:8px;grid-row:1/-1">Loading...</div>');
            $.ajax({
                url: 'https://platform.instinctor.com/api/graphics',
                method: 'GET',
                data: { category: '3d' },
                dataType: 'json',
                timeout: 15000,
                success: function(data) {
                    _d3InlineCache = (data.graphics || []).filter(function(g) {
                        return !/\d+a$/.test((g.rel_path||'').replace(/\.[^.]+$/,'').split('/').pop()||'');
                    });
                    _render3dInline(_d3InlineCache);
                },
                error: function() { $wrap.html('<div style="color:'+ImpC.dim+';font-size:11px;padding:8px;grid-row:1/-1">Could not load 3D images.</div>'); }
            });
        }

        

        
        var _d3HydrateObserver = null;
        function _d3HydrateOnScroll(wrap, clip) {
            if (!wrap || !clip) return;
            if (_d3HydrateObserver) { try { _d3HydrateObserver.disconnect(); } catch (_e) {} }
            if (typeof IntersectionObserver === 'undefined') {
                
                wrap.querySelectorAll('img[data-src]').forEach(function(im) {
                    im.src = im.getAttribute('data-src');
                    im.removeAttribute('data-src');
                });
                return;
            }
            _d3HydrateObserver = new IntersectionObserver(function(entries) {
                entries.forEach(function(en) {
                    if (!en.isIntersecting) return;
                    var im = en.target;
                    var ds = im.getAttribute('data-src');
                    if (ds) {
                        im.src = ds;
                        im.removeAttribute('data-src');
                    }
                    _d3HydrateObserver.unobserve(im);
                });
            }, { root: clip, rootMargin: '200px 0px', threshold: 0.01 });
            wrap.querySelectorAll('img[data-src]').forEach(function(im) {
                _d3HydrateObserver.observe(im);
            });
        }

        function _render3dInline(images) {
            var $wrap = $('.impulse-3d-presets-wrap');
            if (!$wrap.length) return;
            var curImg = $('input[name="screen_depth_image"]').val() || '';
            if (!images.length) {
                $wrap.html('<div style="color:'+ImpC.dim+';font-size:11px;padding:8px;grid-row:1/-1">No 3D images. Click More.</div>');
                return;
            }
            
            var $clip = $wrap.closest('.impulse-3d-grid-clip');
            var clipW = $clip.length ? Math.floor($clip.width()) : 280;
            var colW = 92, colGap = 5;
            var cols = Math.max(1, Math.floor((clipW + colGap) / (colW + colGap)));

            var visible = images;
            
            if ($clip[0]) $clip[0].scrollLeft = 0;
            var html = '';
            var proLockBuild = window.isProLocked && window.isProLocked();
            visible.forEach(function(img) {
                var isActive = img.image_url === curImg;
                var locked = proLockBuild && img.tier === 'pro';
                var lockedCls = locked ? ' impulse-pro-locked' : '';
                var lockAttrs = locked ? ' data-pro-locked="1" data-pro-label="3D image"' : '';
                html += '<div class="impulse-3d-inline-card' + (isActive ? ' active' : '') + lockedCls + '" data-img-url="' + img.image_url + '" style="cursor:pointer;border-radius:3px;overflow:hidden;border:2px solid ' + (isActive ? ''+ImpC.text+'' : 'transparent') + ';transition:border-color 0.15s;width:' + colW + 'px;height:57px;flex-shrink:0;box-sizing:border-box;position:relative;scroll-snap-align:start;background:'+ImpC.panel+'"' + lockAttrs + '>';

                

                

                

                

                

                

                var _src = img.thumbnail_url || img.image_url;
                html += '<img src="' + _src + '" loading="lazy" decoding="async" width="' + colW + '" height="57" onerror="this.parentNode.style.display=\'none\'" style="width:100%;height:100%;object-fit:cover;display:block;pointer-events:none">';
                html += '</div>';
            });
            $wrap.html(html);

            var _clipEl = $clip[0];
            if (_clipEl && !_clipEl._3dWheelBound) {
                _clipEl._3dWheelBound = true;
                var _colStep = colW + colGap; 
                _clipEl.addEventListener('wheel', function(e) {
                    
                    if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
                    e.preventDefault();
                    this.scrollBy({ left: e.deltaY > 0 ? _colStep : -_colStep, behavior: 'smooth' });
                }, { passive: false });
            }
        }

            var _dep3dSpinner = '<div class="imp3d-depth-spin" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.45);z-index:4;pointer-events:none;border-radius:2px">'                + '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" style="animation:impulse-spin 0.75s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>'                + '</div>';
        $(document).on('click', '.impulse-3d-inline-card', function(e) {
            var $card = $(this);
            var imageUrl = $card.data('img-url');
            
            if ($card.hasClass('active')) {
                $('input[name="screen_cloud_effect"]').val('');
                if (Impulse.pageSettings) Impulse.pageSettings.screen_cloud_effect = ''; 
                $('input[name="screen_depth_image"]').val('');
                $('input[name="screen_depth_map"]').val('');
                $('input[name="screen_depth_enabled"]').val('0');
                if (Impulse.pageSettings) { Impulse.pageSettings.screen_depth_image = ''; Impulse.pageSettings.screen_depth_map = ''; Impulse.pageSettings.screen_depth_enabled = '0'; } 
                $('.impulse-3d-inline-card').css('border-color', 'transparent').removeClass('active');
                $card.find('.imp3d-depth-spin').remove();
                var _dsOff = collectSettingsFromPanel(Impulse.pageSettings || {});
                Impulse.pageSettings = _dsOff;
                applyPageSettingsToPreview(_dsOff);
                saveScreenBarSettings(false);
                var _ifrEl0 = document.getElementById('impulse-iframe');
                if (_ifrEl0 && _ifrEl0.contentWindow && _ifrEl0.contentWindow.ImpulseDepthParallax) {
                    var _ifrDoc0 = _ifrEl0.contentDocument || _ifrEl0.contentWindow.document;
                    if (_ifrDoc0 && _ifrDoc0.body) {
                        _ifrDoc0.body.removeAttribute('data-depth-image');
                        _ifrDoc0.body.removeAttribute('data-depth-map');
                        _ifrDoc0.body.removeAttribute('data-depth-strength');
                        _ifrDoc0.body.setAttribute('data-screen-cloud-effect', '');
                        _ifrDoc0.body.setAttribute('data-depth-enabled', '0');
                        _ifrEl0.contentWindow.ImpulseDepthParallax.destroyAll();
                    }
                }
                return;
            }
            var pairedDepth = imageUrl.replace(/(\.[^\/\.]+)$/, 'a.png');
            $('input[name="screen_cloud_effect"]').val('depth_image');
            if (Impulse.pageSettings) Impulse.pageSettings.screen_cloud_effect = 'depth_image'; 
            $('input[name="screen_depth_image"]').val(imageUrl);
            $('input[name="screen_depth_enabled"]').val('1');
            $('input[name="screen_depth_free"]').val('1');

            

            
            if (Impulse.pageSettings) {
                Impulse.pageSettings.screen_depth_image   = imageUrl;
                Impulse.pageSettings.screen_depth_enabled = '1';
                Impulse.pageSettings.screen_depth_free    = '1';
            }
            $('.impulse-3d-inline-card').css('border-color', 'transparent').removeClass('active');
            $(this).css('border-color', ''+ImpC.text+'').addClass('active');

            var _dsNow = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = _dsNow;
            applyPageSettingsToPreview(_dsNow);
            saveScreenBarSettings(false);

            $(this).find('.imp3d-depth-spin').remove();
            $(this).append(_dep3dSpinner);

            _saveDepthMapLocally(pairedDepth, imageUrl, function(localDepth) {
                
                $('.imp3d-depth-spin').remove();
                if (!localDepth) return;
                $('input[name="screen_depth_map"]').val(localDepth);
                if (Impulse.pageSettings) Impulse.pageSettings.screen_depth_map = localDepth; 
                var _ds = collectSettingsFromPanel(Impulse.pageSettings || {});
                Impulse.pageSettings = _ds;
                applyPageSettingsToPreview(_ds);
                if (typeof reinitTunnelFromSettings === 'function') reinitTunnelFromSettings(_ds);
                saveScreenBarSettings(false);
                var _ifrEl = document.getElementById('impulse-iframe');
                if (_ifrEl && _ifrEl.contentWindow && _ifrEl.contentWindow.ImpulseDepthParallax) {
                    var _ifrDoc = _ifrEl.contentDocument || _ifrEl.contentWindow.document;
                    if (_ifrDoc && _ifrDoc.body) {
                        _ifrDoc.body.setAttribute('data-depth-image', imageUrl);
                        _ifrDoc.body.setAttribute('data-depth-map', localDepth);
                        _ifrDoc.body.setAttribute('data-depth-strength', (function(v){ return (v === undefined || v === '') ? '50' : v; })($('input[name="screen_depth_strength"]').val()));
                        _ifrDoc.body.setAttribute('data-screen-cloud-effect', 'depth_image');
                        _ifrDoc.body.setAttribute('data-depth-enabled', '1');
                        _ifrEl.contentWindow.ImpulseDepthParallax.destroyAll();
                        _ifrEl.contentWindow.ImpulseDepthParallax.init(_ifrDoc.body);
                    }
                }
            });
        });

        

        

        
        $(document).on('impulse:preview:loaded', function() {
            if (window.ImpulseTimelineEditor) {
                setTimeout(function(){ window.ImpulseTimelineEditor.render(); }, 100);
            }
        });

        

        $(document).on('click', '#impulse-sequence-toggle', function() {
            var $body = $('#impulse-sequence-body');
            var collapsed = $body.is(':visible'); 
            $body.toggle(!collapsed);
            $('#impulse-sequence-chevron').css('transform', collapsed ? 'rotate(-90deg)' : '');
            $(this).attr('title', collapsed ? 'Click to expand' : 'Click to collapse');
            try { localStorage.setItem('impulse_scene_panel_collapsed', collapsed ? '1' : '0'); } catch(_e) {}
        });

        $(document).on('click', '#impulse-add-screen-btn', function() {

            

            

            

            

            var defaultSettings = { bg_color: 'transparent', justify: 'center', align: 'center' };
            var afterRender = function(newId) {
                window._impulseNavigateToNewScreen = newId;
                refreshPreview();
            };
            var siblingId = getActiveScreenId();
            if (siblingId) {
                addElementWithSettingsNearSibling('section', defaultSettings, siblingId, 'after', afterRender);
            } else {
                
                addElementWithSettings('section', defaultSettings, null, 999999, afterRender);
            }
        });

        $(document).on('click', '.impulse-ps-toggle', function() {
            var targetId = $(this).data('target');
            var $target = $('#' + targetId + ', .' + targetId);
            var isOpening = !$target.is(':visible');
            $target.slideToggle(150);
            $(this).find('span:last').text(isOpening ? '▾' : '▸');
            
            $(this).find('.impulse-sequence-chevron').css('transform', isOpening ? 'rotate(0deg)' : 'rotate(-90deg)');
            if (isOpening) {
                $('.impulse-bg-animation-settings').slideUp(150);
            }
        });
        
        function applyPageSettingsToPreview(settings) {
            var _isScreenMode = true;
            
            $('.impulse-canvas').attr('data-screen-mode', _isScreenMode ? '1' : '0');
            
            var iframe = document.getElementById('impulse-iframe');
            
            if (iframe && _isScreenMode) iframe.style.height = '';
            if (!iframe || !iframe.contentDocument) return;
            
            try {
                var doc = iframe.contentDocument || iframe.contentWindow.document;
                var body = doc.body;
                if (!body) return;

                var device = window.impulseDevice || 'desktop';
                var resolvedSettings = resolveDeviceSettings(settings, device);

                
                if (typeof window.IMPULSE_PAGE_AUTO_SCALE === 'function') {
                    resolvedSettings = window.IMPULSE_PAGE_AUTO_SCALE(resolvedSettings, settings, device);
                }

                if (_isScreenMode) {
                    body.setAttribute('data-screen-mode', '1');
                } else {
                    body.removeAttribute('data-screen-mode');
                }

                var htmlEl = doc.documentElement;
                var _bgVal = resolvedSettings.bg_color || '';
                if (_isScreenMode) {
                    var _cloudEff2 = settings.screen_cloud_effect || 'none';
                    var _isPaletteCloud2 = ['wave','clouds'].indexOf(_cloudEff2) !== -1;
                    var _bgLocked2 = ['cosmos','neon','caustics','glass','bubble','flow','aurora','clouds','aura','topography','lava','blob','fractal','bubble','noise','ripple','swirl','kaleidoscope','columns','turing'];
                    var _effectiveBg;
                    if (_bgLocked2.indexOf(_cloudEff2) !== -1) {
                        _effectiveBg = '#000000';
                    } else if (_cloudEff2 === 'depth_image') {
                        _effectiveBg = 'transparent';
                    } else if (_isPaletteCloud2) {
                        _effectiveBg = '#ffffff';
                    } else if (_cloudEff2 === 'none' || !_cloudEff2) {

                        

                        _effectiveBg = (_bgVal && _bgVal !== 'transparent') ? _bgVal : ''+ImpC.light+'';
                    } else {
                        var _perEffBg = settings['screen_' + _cloudEff2 + '_bg_color'];
                        _effectiveBg = (_perEffBg && _perEffBg !== 'transparent') ? _perEffBg
                            : (_bgVal && _bgVal !== 'transparent') ? _bgVal : ''+ImpC.light+'';
                    }

                    

                    

                    
                    var _pgClassicBg = (((settings && settings.body_scroll) || (window.Impulse && Impulse.pageSettings && Impulse.pageSettings.body_scroll)) === 'classic');
                    if (_pgClassicBg) {
                        var _authClassicBg = (_bgVal && _bgVal !== 'transparent') ? _bgVal
                            : (window.Impulse && Impulse.pageSettings && Impulse.pageSettings.bg_color && Impulse.pageSettings.bg_color !== 'transparent') ? Impulse.pageSettings.bg_color
                            : '';
                        _effectiveBg = _authClassicBg ? _authClassicBg : ''+ImpC.light+'';
                    }
                    htmlEl.style.setProperty('background', _effectiveBg, 'important');
                    body.style.setProperty('background', 'transparent', 'important');
                    body.setAttribute('data-page-bg-color', _effectiveBg);
                    body.dataset.pageBgColor = _effectiveBg;

                    
                    var _fxBgLocked = ['cosmos','neon','caustics','glass','bubble','flow','aurora','clouds','aura','topography','lava','blob','fractal','noise','ripple','swirl','kaleidoscope','turing'];
                    if (_fxBgLocked.indexOf(_cloudEff2) === -1 && !_isPaletteCloud2) {
                        var _apFX = iframe.contentWindow && iframe.contentWindow._impulseFX;
                        if (_apFX && _apFX.update) _apFX.update({ bgColor: _effectiveBg });
                    }
                } else {

                    

                    

                    

                    

                    
                    
                    var _hasMeaningfulBg = (typeof _bgVal === 'string' && _bgVal !== '');
                    if (_hasMeaningfulBg) {
                        var _resolvedBg = (_bgVal === 'transparent') ? '#ffffff' : _bgVal;
                        body.style.backgroundColor = _resolvedBg;
                        htmlEl.style.background = '';
                        body.setAttribute('data-page-bg-color', _resolvedBg);
                    }
                }

                var paddingTop = resolvedSettings.padding_top !== undefined ? resolvedSettings.padding_top : 0;
                var paddingRight = resolvedSettings.padding_right !== undefined ? resolvedSettings.padding_right : 0;
                var paddingBottom = resolvedSettings.padding_bottom !== undefined ? resolvedSettings.padding_bottom : 0;
                var paddingLeft = resolvedSettings.padding_left !== undefined ? resolvedSettings.padding_left : 0;
                
                var contentWrapper = body.querySelector('.impulse-content-wrapper');
                if (contentWrapper) {
                    contentWrapper.style.paddingTop = paddingTop + 'px';
                    contentWrapper.style.paddingRight = paddingRight + 'px';

                    

                    
                    
                    contentWrapper.style.paddingBottom = '0px';
                    contentWrapper.style.paddingLeft = paddingLeft + 'px';
                }

                body.style.setProperty('--impulse-padding-top', paddingTop + 'px');
                body.style.setProperty('--impulse-padding-left', paddingLeft + 'px');
                body.style.setProperty('--impulse-padding-right', paddingRight + 'px');
                body.style.setProperty('--impulse-padding-bottom', paddingBottom + 'px');

                var spacing = resolvedSettings.element_spacing !== undefined ? resolvedSettings.element_spacing : 20;
                if (contentWrapper) {
                    contentWrapper.style.gap = spacing + 'px';
                }
                body.style.setProperty('--impulse-element-spacing', spacing + 'px');

                var contentWidth = resolvedSettings.content_width !== undefined ? resolvedSettings.content_width : 100;
                var maxContentWidth = resolvedSettings.max_content_width !== undefined ? parseInt(resolvedSettings.max_content_width) : 1440;
                var maxWidth = contentWidth + '%';

                body.style.setProperty('--impulse-content-max-width', maxContentWidth > 0 ? maxContentWidth + 'px' : 'none');

                
                var containers = doc.querySelectorAll('.impulse-container');
                for (var c = 0; c < containers.length; c++) {
                    containers[c].style.maxWidth = maxContentWidth > 0 ? maxContentWidth + 'px' : 'none';
                    containers[c].style.marginLeft = 'auto';
                    containers[c].style.marginRight = 'auto';
                }

                

                if (contentWrapper) {
                    var children = contentWrapper.children;
                    for (var i = 0; i < children.length; i++) {
                        var child = children[i];

                        

                        

                        
                        
                        var isSectionWrapper = child.classList.contains('impulse-el') &&
                            child.getAttribute('data-type') === 'section';
                        if (!child.classList.contains('impulse-section') &&
                            !child.classList.contains('impulse-dropzone') &&
                            !isSectionWrapper &&
                            child.tagName !== 'SCRIPT' &&
                            child.tagName !== 'STYLE') {
                            child.style.maxWidth = maxWidth;
                            child.style.marginLeft = 'auto';
                            child.style.marginRight = 'auto';
                        }
                    }
                }
            } catch (e) {}

            try {
                var doc2 = iframe.contentDocument || iframe.contentWindow.document;
                if (doc2 && doc2.body) {
                    var screenStyleId = 'impulse-screen-mode-style';
                    var existingStyle = doc2.getElementById(screenStyleId);
                    
                    if (_isScreenMode) {
                        doc2.body.setAttribute('data-screen-mode', '1');
                        doc2.body.setAttribute('data-screen-transition', settings.screen_transition || 'z_depth');
                        doc2.body.setAttribute('data-screen-cooldown', settings.screen_cooldown || 150);
                        doc2.body.setAttribute('data-screen-duration', settings.screen_duration || 700);
                        doc2.body.setAttribute('data-screen-intensity', settings.screen_intensity !== undefined ? settings.screen_intensity : 50);
                        if (settings.nav_dots) {
                            doc2.body.setAttribute('data-screen-nav-dots', '1');
                        } else {
                            doc2.body.removeAttribute('data-screen-nav-dots');
                        }

                        
                        
                        var screenWrapper = doc2.querySelector('.impulse-screen-wrapper');
                        if (screenWrapper) {
                            screenWrapper.dataset.tunnel = (settings.screen_tunnel === '1' || settings.screen_tunnel === 1 || settings.screen_tunnel === true) ? '1' : '0';
                            screenWrapper.dataset.cloudEffect = settings.screen_cloud_effect || 'none';
                            screenWrapper.dataset.neonSides    = settings.screen_neon_sides || '4';
                            screenWrapper.dataset.neonHue      = settings.screen_effect_hue !== undefined ? settings.screen_effect_hue : '-1';
                            screenWrapper.dataset.tunnelSpeed = settings.screen_tunnel_speed || '1';
                            screenWrapper.dataset.tunnelFill = settings.screen_tunnel_fill == '1' ? '1' : '0';
                            screenWrapper.dataset.mouseSensLevel = ((settings.screen_mouse_sens_level !== undefined ? parseFloat(settings.screen_mouse_sens_level) : 5) / 10).toFixed(2);
                            screenWrapper.dataset.bwElementSize = settings.screen_bw_element_size || '100';
                            screenWrapper.dataset.bwElementCount = settings.screen_bw_element_count || '50';
                            screenWrapper.dataset.bwAccentColor = settings.screen_bw_accent_color || '';
                            screenWrapper.dataset.lavaColor1 = settings.screen_lava_color1 || '#333333';
                            screenWrapper.dataset.lavaColor2 = settings.screen_lava_color2 || '#999999';
                            screenWrapper.dataset.lavaColor3 = settings.screen_lava_color3 || '#666666';
                            screenWrapper.dataset.lavaColor4 = settings.screen_lava_color4 || '#cccccc';
                            screenWrapper.dataset.lavaSpeed  = settings.screen_lava_speed || '10';
                            screenWrapper.dataset.lavaIntensity = settings.screen_lava_intensity || '5';
                            screenWrapper.dataset.waveColor1 = settings.screen_wave_color1 || '#6b8eff';
                            screenWrapper.dataset.waveColor2 = settings.screen_wave_color2 || '#e256a0';
                            screenWrapper.dataset.waveColor3 = settings.screen_wave_color3 || '#ff8054';
                            screenWrapper.dataset.waveColor4 = settings.screen_wave_color4 || '#9333ea';
                            screenWrapper.dataset.waveSpeed  = settings.screen_wave_speed || '10';
                            screenWrapper.dataset.wavePreset = settings.screen_wave_preset || 'flow';
                            screenWrapper.dataset.waveIntensity = settings.screen_wave_intensity || '10';

                            var _wEff3d = settings.screen_cloud_effect || 'none';
                            var _wp3d = function(suffix) { return settings['screen_' + _wEff3d + '_' + suffix]; };
                            screenWrapper.dataset['3dColor1']    = _wp3d('color1') || '#333333';
                            screenWrapper.dataset['3dColor2']    = _wp3d('color2') || '#999999';
                            screenWrapper.dataset['3dColor3']    = _wp3d('color3') || '#666666';
                            screenWrapper.dataset['3dColor4']    = _wp3d('color4') || '#cccccc';
                            screenWrapper.dataset['3dSpeed']     = _wp3d('speed') || '10';
                            screenWrapper.dataset['3dPreset']    = _wp3d('preset') || '';
                            screenWrapper.dataset['3dIntensity'] = _wp3d('intensity') || '10';
                            screenWrapper.dataset['prismBg'] = settings.screen_prism_bg || '';
                            screenWrapper.dataset['prismShape'] = settings.screen_prism_shape || '0';
                            screenWrapper.dataset['pageBgColor'] = (settings.bg_color && settings.bg_color !== 'transparent') ? settings.bg_color : ''+ImpC.light+'';
                        }
                        
                        doc2.body.setAttribute('data-screen-tunnel', (settings.screen_tunnel === '1' || settings.screen_tunnel === 1 || settings.screen_tunnel === true) ? '1' : '0');
                        doc2.body.setAttribute('data-screen-cloud-effect', settings.screen_cloud_effect || 'none');
                        
                        var _dpIfrEl = document.getElementById('impulse-iframe');
                        if (_dpIfrEl && _dpIfrEl.contentWindow && _dpIfrEl.contentWindow.ImpulseDepthParallax) {
                            var _dp = _dpIfrEl.contentWindow.ImpulseDepthParallax;

                            
                            
                            var _isDepthEff = (settings.screen_cloud_effect === 'depth_image'
                                              || settings.screen_cloud_effect === 'glass') &&
                                              settings.screen_depth_image && settings.screen_depth_map;
                            var _prevImg = _dpIfrEl._lastDepthImage;
                            var _prevMap = _dpIfrEl._lastDepthMap;
                            var _depthChanged = _prevImg !== settings.screen_depth_image || _prevMap !== settings.screen_depth_map;
                            if (_isDepthEff) {
                                doc2.body.setAttribute('data-depth-image',    settings.screen_depth_image);
                                doc2.body.setAttribute('data-depth-map',      settings.screen_depth_map);
                                doc2.body.setAttribute('data-depth-strength', ((settings.screen_depth_strength === undefined || settings.screen_depth_strength === null || settings.screen_depth_strength === '') ? '50' : String(settings.screen_depth_strength)));
                                if (_depthChanged) {
                                    _dp.destroyAll();
                                    _dp.init(doc2.body);
                                    _dpIfrEl._lastDepthImage = settings.screen_depth_image;
                                    _dpIfrEl._lastDepthMap   = settings.screen_depth_map;
                                }
                                
                                var _cw = doc2.querySelector('.impulse-content-wrapper,.impulse-page');
                                if (_cw) _cw.style.zIndex = '2';
                            } else if (_prevImg || _prevMap) {
                                
                                _dp.destroyAll();
                                _dpIfrEl._lastDepthImage = null;
                                _dpIfrEl._lastDepthMap   = null;
                                var _cw2 = doc2.querySelector('.impulse-content-wrapper,.impulse-page');
                                if (_cw2) _cw2.style.zIndex = '';
                            }
                        }
                        doc2.body.setAttribute('data-screen-neon-sides', settings.screen_neon_sides || '4');
                        doc2.body.setAttribute('data-screen-neon-hue',   settings.screen_effect_hue !== undefined ? settings.screen_effect_hue : '-1');
                        doc2.body.setAttribute('data-screen-tunnel-fill', settings.screen_tunnel_fill == '1' ? '1' : '0');
                        doc2.body.setAttribute('data-screen-mouse-sens-level', ((settings.screen_mouse_sens_level !== undefined ? parseFloat(settings.screen_mouse_sens_level) : 5) / 10).toFixed(2));
                        doc2.body.setAttribute('data-screen-bw-element-size', settings.screen_bw_element_size || '100');
                        doc2.body.setAttribute('data-screen-bw-element-count', settings.screen_bw_element_count || '50');
                        doc2.body.setAttribute('data-screen-bw-accent-color', settings.screen_bw_accent_color || '');
                        doc2.body.setAttribute('data-screen-space-variant', settings.screen_space_variant || '');
                        doc2.body.setAttribute('data-screen-lava-color1', settings.screen_lava_color1 || '#333333');
                        doc2.body.setAttribute('data-screen-lava-color2', settings.screen_lava_color2 || '#999999');
                        doc2.body.setAttribute('data-screen-lava-color3', settings.screen_lava_color3 || '#666666');
                        doc2.body.setAttribute('data-screen-lava-color4', settings.screen_lava_color4 || '#cccccc');
                        doc2.body.setAttribute('data-screen-lava-speed',  settings.screen_lava_speed || '10');
                        doc2.body.setAttribute('data-screen-lava-intensity', settings.screen_lava_intensity || '5');

                        

                        
                        var _ifWin = iframe.contentWindow;
                        var _lavaEng = _ifWin && _ifWin._impulseMotionLava;
                        if (_lavaEng) {
                            try {
                                if (_lavaEng.updateColors) _lavaEng.updateColors([
                                    settings.screen_lava_color1 || '#333333',
                                    settings.screen_lava_color2 || '#999999',
                                    settings.screen_lava_color3 || '#666666',
                                    settings.screen_lava_color4 || '#cccccc'
                                ]);
                                if (_lavaEng.updateSpeed) _lavaEng.updateSpeed((parseInt(settings.screen_lava_speed) || 10) / 10);
                            } catch (_e) {  }
                        }
                        doc2.body.setAttribute('data-screen-wave-color1', settings.screen_wave_color1 || '#6b8eff');
                        doc2.body.setAttribute('data-screen-wave-color2', settings.screen_wave_color2 || '#e256a0');
                        doc2.body.setAttribute('data-screen-wave-color3', settings.screen_wave_color3 || '#ff8054');
                        doc2.body.setAttribute('data-screen-wave-color4', settings.screen_wave_color4 || '#9333ea');
                        doc2.body.setAttribute('data-screen-wave-speed',  settings.screen_wave_speed || '10');
                        doc2.body.setAttribute('data-screen-wave-preset', settings.screen_wave_preset || 'flow');
                        doc2.body.setAttribute('data-screen-wave-intensity', settings.screen_wave_intensity || '10');

                        
                        var _curEff3d = settings.screen_cloud_effect || 'none';
                        var _p3d = function(suffix) { return settings['screen_' + _curEff3d + '_' + suffix]; };
                        var _c3d1 = _p3d('color1') || '#333333';
                        var _c3d2 = _p3d('color2') || '#999999';
                        var _c3d3 = _p3d('color3') || '#666666';
                        var _c3d4 = _p3d('color4') || '#cccccc';
                        var _s3d  = _p3d('speed') || '10';
                        var _bg3d = settings['screen_' + _curEff3d + '_bg_color'] || '';
                        doc2.body.setAttribute('data-screen-3d-color1', _c3d1);
                        doc2.body.setAttribute('data-screen-3d-color2', _c3d2);
                        doc2.body.setAttribute('data-screen-3d-color3', _c3d3);
                        doc2.body.setAttribute('data-screen-3d-color4', _c3d4);
                        doc2.body.setAttribute('data-screen-3d-speed',     _s3d);
                        doc2.body.setAttribute('data-screen-3d-preset',    _p3d('preset') || '');
                        doc2.body.setAttribute('data-screen-3d-intensity', _p3d('intensity') || '10');
                        doc2.body.setAttribute('data-screen-3d-count', _p3d('count') || '7');
                        doc2.body.setAttribute('data-screen-3d-variation', _p3d('variation') || '3');
                        doc2.body.setAttribute('data-screen-3d-density', _p3d('density') || '7');
                        doc2.body.setAttribute('data-screen-3d-halo', _p3d('halo') || '4');

                        

                        

                        var _3dEng = iframe.contentWindow && iframe.contentWindow._impulse3D;
                        if (_3dEng) {
                            try {
                                if (_3dEng.updateColors) _3dEng.updateColors([_c3d1, _c3d2, _c3d3, _c3d4]);
                                if (_3dEng.updateSpeed)  _3dEng.updateSpeed((parseInt(_s3d) || 10) / 10);
                                if (_3dEng.updateBgColor && _bg3d) _3dEng.updateBgColor(_bg3d);

                                if (_curEff3d === 'grid' && _3dEng._gridRebuild) {
                                    _3dEng.intensity = (parseInt(_p3d('intensity')) || 1) / 10;
                                    _3dEng._count = parseInt(_p3d('count')) || 7;
                                    _3dEng._variation = _p3d('variation') !== undefined && _p3d('variation') !== '' ? parseInt(_p3d('variation')) : 3;
                                    _3dEng._gridRebuild();
                                    if (_3dEng._gridSetDensity) _3dEng._gridSetDensity(_p3d('density') !== undefined && _p3d('density') !== '' ? parseInt(_p3d('density')) : 7);
                                }
                                
                                if (_curEff3d === 'asteroid' && _3dEng.material && _3dEng.material.uniforms.u_halo) {
                                    var _hv = _p3d('halo') !== undefined && _p3d('halo') !== '' ? parseInt(_p3d('halo')) : 4;
                                    _3dEng.material.uniforms.u_halo.value = Math.max(0, Math.min(1, _hv / 10));
                                }
                            } catch (_e3d) {  }
                        }
                        doc2.body.setAttribute('data-screen-prism-bg', settings.screen_prism_bg || '');
                        doc2.body.setAttribute('data-screen-prism-shape', settings.screen_prism_shape || '0');
                        
                        var IS = iframe.contentWindow && iframe.contentWindow.ImpulseScreens;
                        if (IS) {
                            IS.updateSettings(
                                settings.screen_transition || 'z_depth',
                                parseInt(settings.screen_cooldown) || 150,
                                parseInt(settings.screen_duration) || 700,
                                !!settings.nav_dots,
                                settings.screen_intensity !== undefined ? parseInt(settings.screen_intensity) : 50,
                                !!(settings.screen_infinite_loop == '1' || settings.screen_infinite_loop === 1 || settings.screen_infinite_loop === true),
                                parseFloat(settings.screen_tunnel_speed) || 1,
                                !!(settings.screen_tunnel == '1' || settings.screen_tunnel === 1 || settings.screen_tunnel === true)
                            );
                        }
                        
                    } else {
                        doc2.body.removeAttribute('data-screen-mode');
                        doc2.body.removeAttribute('data-screen-transition');
                        doc2.body.removeAttribute('data-screen-cooldown');
                        doc2.body.removeAttribute('data-screen-duration');
                        doc2.body.removeAttribute('data-screen-intensity');
                        doc2.body.removeAttribute('data-screen-nav-dots');
                        if (existingStyle) existingStyle.remove();
                        var navDots = doc2.querySelector('.impulse-screen-nav');
                        if (navDots) navDots.remove();
                    }
                }
            } catch(e2) {}

            

            

            

            if (typeof _liveUpdateGradientOverlay === 'function') {
                setTimeout(_liveUpdateGradientOverlay, 0);
            }
        }

        function setDevice(device) {
            if (device === currentDevice) return;

            

            

            
            
            var currentId = $('.impulse-panel-right').data('element-id');
            if (currentId && selectedElementType && 
                !isPageSettingsMode() &&
                $('#impulse-settings-body').text().indexOf('Loading') === -1) {
                
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var currentSettings = collectSettingsFromPanel(existingSettings);

                $('.impulse-panel-right').data('existing-settings', currentSettings);

                $.ajax({
                    url: Impulse.api + 'elements/' + currentId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: currentSettings, page_id: Impulse.pageId }),
                    async: false
                });
            }

            

            

            

            if (isPageSettingsMode()) {
                var currentSettings = collectSettingsFromPanel(Impulse.pageSettings || {});
                Impulse.pageSettings = currentSettings;
                $('.impulse-panel-right').data('existing-settings', currentSettings);
            }

            currentDevice = device;
            window.impulseDevice = device;
            sessionStorage.setItem('impulseDevice', device);

            if (window.siteHeaderPrev && Object.keys(window.siteHeaderPrev).length) {
                window.siteHeaderPrev.__device = (device === 'desktop' ? 'mobile' : 'desktop');
            }
            if (window.siteFooterPrev && Object.keys(window.siteFooterPrev).length) {
                window.siteFooterPrev.__device = (device === 'desktop' ? 'mobile' : 'desktop');
            }

            $('.impulse-device-tab').removeClass('active');
            $('.impulse-device-tab[data-device="' + device + '"]').addClass('active');

            $('.impulse-canvas').attr('data-device', device);

            
            
            var _smNowDS = Impulse.pageSettings && (true);
            $('.impulse-canvas').attr('data-screen-mode', _smNowDS ? '1' : '0');

            
            
            var _ifrDS = document.getElementById('impulse-iframe');
            if (_ifrDS) _ifrDS.style.height = '';

            
            
            var $canvas = $('.impulse-canvas');
            $canvas.css('transform', '');

            
            viewportPreserve.capture();
            refreshPreview();

            if (_smNowDS) {
                [80, 300, 800].forEach(function(ms) {
                    setTimeout(function() {
                        if (typeof window.fitScreenCanvas === 'function') window.fitScreenCanvas();
                    }, ms);
                });
            }

            if (selectedElementId && selectedElementType) {
                openSettings(selectedElementId, selectedElementType);
            }

            if (isPageSettingsMode()) {

                
                var settings = Impulse.pageSettings || {};
                _showCurrentScreenSettings();
                applyPageSettingsToPreview(settings);
            }
        }

        $(document).on('click', '.impulse-device-tab', function() {

            

            
            var _ifrDev = document.getElementById('impulse-iframe');
            if (_ifrDev) _ifrDev.style.pointerEvents = '';
            setDevice($(this).data('device'));
        });

        
        function executeRedo(item) {
            switch (item.action) {
                case 'add':
                    var addResp = $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({
                            element_type: item.data.elementType,
                            parent_id: item.data.parentId,
                            sort_order: item.data.sortOrder,
                            settings: item.data.settings || {}
                        }),
                        async: false
                    });
                    if (addResp.responseJSON && addResp.responseJSON.id) {
                        item.data.elementId = addResp.responseJSON.id;
                    }
                    break;
                case 'delete':
                    $.ajax({
                        url: Impulse.api + 'elements/' + item.data.elementId,
                        method: 'DELETE',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        async: false
                    });
                    break;
                case 'update':
                    $.ajax({
                        url: Impulse.api + 'elements/' + item.data.elementId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: item.data.newSettings, page_id: Impulse.pageId }),
                        async: false
                    });
                    break;
                case 'reorder':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + item.data.sourceId + '/reorder',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({
                            target_id: item.data.targetId,
                            position: item.data.position
                        }),
                        async: false
                    });
                    break;
                case 'move':
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + item.data.sourceId + '/move-into',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify((function(){ var b={parent_id:item.data.targetId,page_id:Impulse.pageId||0}; if(item.data.gridCellIndex!=null)b.grid_cell_index=item.data.gridCellIndex; if(item.data.cellRow!=null)b.cell_row=item.data.cellRow; if(item.data.cellCol!=null)b.cell_col=item.data.cellCol; if(item.data.slideIndex!=null)b.slide_index=item.data.slideIndex; return b; })()),
                        async: false
                    });
                    break;
            }
            refreshPreview();
        }

        function isResponsiveSetting(name) {
            if (!window.RESPONSIVE_SETTINGS) return false;
            
            if (window.RESPONSIVE_SETTINGS.indexOf(name) !== -1) return true;
            
            for (var i = 0; i < window.RESPONSIVE_SETTINGS.length; i++) {
                var setting = window.RESPONSIVE_SETTINGS[i];
                if (name.endsWith('_' + setting) || name === setting) {
                    return true;
                }
            }
            return false;
        }

        function collectSettingsFromPanel(existingSettings) {

            

            var device = $('.impulse-panel-right').attr('data-panel-device') || window.impulseDevice || 'desktop';

            var debug = window.impulseDebug || false;
            if (debug) console.log('[collectSettings] device:', device);

            existingSettings = existingSettings || $('.impulse-panel-right').data('existing-settings') || {};

            var settings = $.extend(true, {}, existingSettings);

            var $bodyInputs = $('#impulse-settings-body input, #impulse-settings-body select, #impulse-settings-body textarea');
            var $barInputs = $('#impulse-screen-bar').is(':visible') ? $('#impulse-screen-bar input, #impulse-screen-bar select, #impulse-screen-bar textarea') : $();
            var $inputs = $bodyInputs.add($barInputs);
            $inputs.each(function() {
                var name = $(this).attr('name');
                
                if (!name || name.endsWith('_hex') || name.endsWith('_picker')) return;
                
                if (name.endsWith('_opacity') && $(this).closest('.impulse-color-picker').length) return;
                
                if (name.indexOf('_link_label') !== -1 || name.indexOf('_link_url') !== -1) return;
                
                if (name.startsWith('menu_label') || name.startsWith('menu_url')) return;

                
                if ($(this).attr('type') !== 'hidden') {
                    if ($(this).closest('[style*="display:none"], [style*="display: none"]').length) return;
                }
                var value;
                if ($(this).attr('type') === 'checkbox') {
                    value = $(this).is(':checked');
                } else if ($(this).attr('type') === 'number' || $(this).attr('type') === 'range') {
                    var _rv = parseFloat($(this).val()) || 0;
                    
                    if (name === 'la_duration' || name === 'la_delay') {
                        value = Math.round(_rv * 1000);
                    } else {

                        

                        
                        var _step = parseFloat($(this).attr('step'));
                        value = (_step && _step < 1) ? _rv : (parseInt(_rv) || 0);
                    }
                } else if ($(this).attr('type') === 'color') {
                    
                    return;
                } else {
                    value = $(this).val();
                }

                

                

                

                
                
                var _impDefault = $(this).attr('data-impulse-default');
                if (typeof _impDefault === 'string' && _impDefault !== '' && value === _impDefault) {
                    value = '';
                }

                
                var $row = $(this).closest('.impulse-setting-row');
                var $sliderRow = $(this).closest('.impulse-slider-row');
                var $richtextSlider = $(this).closest('.impulse-richtext-size-slider');
                var hasDataResponsive = $row.attr('data-responsive') === 'true' || $sliderRow.attr('data-responsive') === 'true' || $richtextSlider.attr('data-responsive') === 'true';
                var isResponsive = hasDataResponsive || isResponsiveSetting(name);

                

                
                
                var _resetUnset = $(this).attr('data-reset-unset') === '1';

                

                

                

                

                

                

                
                
                if (name === 'screen_cloud_effect' && Impulse.pageSettings && typeof Impulse.pageSettings.screen_cloud_effect !== 'undefined') {
                    value = Impulse.pageSettings.screen_cloud_effect;
                }
                var _isAssetRefKey = (
                    name === 'screen_depth_map'  ||
                    name === 'screen_depth_image' ||
                    name === 'bg_depth_map'      ||
                    name === 'bg_depth_image'    ||
                    
                    name === 'screen_cloud_effect'
                );
                if (_isAssetRefKey && (value === '' || value === null || value === undefined)) {
                    if (debug) console.log('[collectSettings] preserve (asset-ref empty):', name);
                    return; 
                }

                if (isResponsive) {

                    
                    if (device === 'desktop') {
                        if (_resetUnset) { delete settings[name]; if (debug) console.log('[collectSettings] unset (reset):', name); }
                        else { settings[name] = value; if (debug) console.log('[collectSettings] responsive desktop:', name, '=', value); }
                    } else {

                        

                        

                        

                        

                        
                        
                        var deviceKey = name + '_' + device;
                        var desktopVal = settings[name];

                        var sameAsDesktop = (desktopVal !== undefined && desktopVal !== null)
                            && String(value) === String(desktopVal);
                        if (_resetUnset || sameAsDesktop) {
                            delete settings[deviceKey];
                            if (debug) console.log('[collectSettings] unset', deviceKey, _resetUnset ? '(reset)' : '(matches desktop)');
                        } else {
                            settings[deviceKey] = value;
                            if (debug) console.log('[collectSettings] responsive', device + ':', deviceKey, '=', value, '(base preserved:', desktopVal, ')');
                        }
                        
                    }
                } else {
                    if (_resetUnset) delete settings[name];
                    else settings[name] = value;
                }
            });

            $('#impulse-settings-body .impulse-color-text, #impulse-screen-bar .impulse-color-text').each(function() {
                var name = $(this).attr('name');
                var val = $(this).val();
                if (name && val) {
                    settings[name] = val;
                }
            });

            $('#impulse-settings-body .impulse-unit-toggle').each(function() {
                var name = $(this).data('name');
                var value = $(this).find('button.active').data('value') || 'px';
                if (name) settings[name] = value;
            });

            if ($('input[name="card_design_elements"]').length) {
                var device = window.impulseDevice || 'desktop';
                settings.card_design = settings.card_design || {};

                var elementsVal = $('input[name="card_design_elements"]').val();
                var elements = [];
                try { elements = JSON.parse(elementsVal || '[]'); } catch(e) { elements = ['image','title','price','add_to_cart','sale_badge','featured_badge']; }
                if (device === 'desktop') {
                    settings.card_design.elements = elements;
                } else {
                    settings.card_design['elements_' + device] = elements;
                }

                
                var _dm = $('input[name="display_mode"]').val() || 'grid';
                if (_dm === 'carousel' || _dm === 'single') {
                    var _cc = parseInt($('input[name="carousel_cards"]').val());
                    if (!isNaN(_cc) && _cc > 0) {
                        if (device === 'tablet') settings.columns_tablet = _cc;
                        else if (device === 'mobile') settings.columns_mobile = _cc;
                        else settings.columns = _cc;
                    }
                }

                function syncElemCb(name, key) {
                    var cb = $('input[name="' + name + '"]').first();
                    if (!cb.length) return;
                    var has = elements.indexOf(key) !== -1;
                    var wants = cb.is(':checked');
                    if (wants && !has) elements.push(key);
                    if (!wants && has) elements = elements.filter(function(e){ return e !== key; });
                    settings[name] = wants;
                }
                syncElemCb('show_sale_badge', 'sale_badge');
                syncElemCb('show_featured_badge', 'featured_badge');
                var _fce = $('input[name="flip_card_effect"]').val() || '';
                settings.flip_card_effect = _fce;
                settings.flip_cards = _fce !== '';
                $('input[name="card_design_elements"]').val(JSON.stringify(elements));
                if (device === 'desktop') settings.card_design.elements = elements;
                else settings.card_design['elements_' + device] = elements;

                settings.card_design.card = {
                    background: $('input[name="card_design_card_background"]').val() || '#ffffff',
                    border_color: $('input[name="card_design_card_border_color"]').val() || ''+ImpC.text+'',
                    border_width: parseInt($('input[name="card_design_card_border_width"]').val()) || 0,
                    border_radius: (function(){ var v=parseInt($('input[name="card_design_card_border_radius"]:visible, input[name="card_design_card_border_radius_manual"]:visible').first().val()); return (!isNaN(v)&&v!==undefined)?v:(function(){ var v2=parseInt($('input[name="card_design_card_border_radius"]').val()); return (!isNaN(v2)&&v2!==undefined)?v2:8; }()); }()),
                    shadow: $('input[name="card_design_card_shadow"]').val() || ''
                };

                var titleSize = parseInt($('input[name="card_design_title_font_size"]').val()) || 16;
                settings.card_design.title = settings.card_design.title || {};
                if (device === 'desktop') {
                    settings.card_design.title.font_size = titleSize;
                } else {
                    settings.card_design.title['font_size_' + device] = titleSize;
                }
                
                var _twEl = $('input[name="card_design_title_font_weight"]');
                if (_twEl.length) settings.card_design.title.font_weight = _twEl.val() || '600';
                settings.card_design.title.color = $('input[name="card_design_title_color"]').val() || ''+ImpC.surface2+'';
                
                settings.card_design.price = settings.card_design.price || {};
                settings.card_design.price.color = settings.card_design.title.color;

                var priceSize = parseInt($('input[name="card_design_price_font_size"]').val()) || 18;
                settings.card_design.price = settings.card_design.price || {};
                if (device === 'desktop') {
                    settings.card_design.price.font_size = priceSize;
                } else {
                    settings.card_design.price['font_size_' + device] = priceSize;
                }
                var _pwEl = $('input[name="card_design_price_font_weight"]');
                if (_pwEl.length) settings.card_design.price.font_weight = _pwEl.val() || '700';
                settings.card_design.price.color = $('input[name="card_design_price_color"]').val() || ''+ImpC.surface2+'';
                settings.card_design.price.sale_color = $('input[name="card_design_price_sale_color"]').val() || '#666666';

                var descSize = parseInt($('input[name="card_design_description_font_size"]').val()) || 13;
                settings.card_design.description = settings.card_design.description || {};
                if (device === 'desktop') {
                    settings.card_design.description.font_size = descSize;
                } else {
                    settings.card_design.description['font_size_' + device] = descSize;
                }
                settings.card_design.description.color = $('input[name="card_design_description_color"]').val() || '#666666';

                var btnSize = parseInt($('input[name="card_design_add_to_cart_font_size"]').val()) || 14;
                settings.card_design.add_to_cart = settings.card_design.add_to_cart || {};
                if (device === 'desktop') {
                    settings.card_design.add_to_cart.font_size = btnSize;
                } else {
                    settings.card_design.add_to_cart['font_size_' + device] = btnSize;
                }
                settings.card_design.add_to_cart.button_text = $('input[name="card_design_add_to_cart_button_text"]').val() || 'Add to Cart';
                settings.card_design.add_to_cart.bg_color = $('input[name="card_design_add_to_cart_bg_color"]').val() || ''+ImpC.surface2+'';
                settings.card_design.add_to_cart.text_color = $('input[name="card_design_add_to_cart_text_color"]').val() || '#ffffff';
                var _brVal = parseInt($('input[name="card_design_add_to_cart_border_radius"]').val());
                settings.card_design.add_to_cart = settings.card_design.add_to_cart || {};
                if (device === 'desktop') {
                    settings.card_design.add_to_cart.border_radius = isNaN(_brVal) ? 6 : _brVal;
                } else {
                    settings.card_design.add_to_cart['border_radius_' + device] = isNaN(_brVal) ? 6 : _brVal;
                }

                settings.card_design.sale_badge = {
                    text: $('input[name="card_design_sale_badge_text"]').val() || 'Sale',
                    featured_text: $('input[name="card_design_featured_badge_text"]').val() || 'Featured',
                    bg_color: $('input[name="card_design_sale_badge_bg_color"]').val() || ''+ImpC.surface2+'',
                    featured_bg_color: $('input[name="card_design_featured_badge_bg_color"]').val() || ''+ImpC.surface2+'',
                    text_color: $('input[name="card_design_sale_badge_text_color"]').val() || '#ffffff'
                };

                Object.keys(settings).forEach(function(k) {
                    if (k.startsWith('card_design_') && k !== 'card_design') {
                        delete settings[k];
                    }
                });
            }

            if ($('input[name="modal_design_gallery_bg"]').length) {
                var device = window.impulseDevice || 'desktop';
                
                var md_existing = (existingSettings && existingSettings.modal_design) ? existingSettings.modal_design : {};
                settings.modal_design = $.extend(true, {}, md_existing);

                var globalNum = ['modal_design_overlay_opacity','modal_design_desc_size'];
                var globalStr = []; 
                globalNum.forEach(function(f) {
                    var k = f.replace('modal_design_', '');
                    settings.modal_design[k] = parseInt($('input[name="' + f + '"]').val()) || 0;
                });
                globalStr.forEach(function(f) {
                    var k = f.replace('modal_design_', '');
                    settings.modal_design[k] = $('input[name="' + f + '"]').val() || '';
                });
                
                var perDeviceNum  = ['modal_design_max_width','modal_design_height','modal_design_border_radius','modal_design_details_padding'];
                var perDeviceBool = ['modal_design_show_price','modal_design_show_qty'];
                perDeviceNum.forEach(function(f) {
                    var k = f.replace('modal_design_', '');
                    var v = parseInt($('input[name="' + f + '"]').val()) || 0;
                    var key = device === 'desktop' ? k : k + '_' + device;
                    settings.modal_design[key] = v;
                });
                perDeviceBool.forEach(function(f) {
                    var k = f.replace('modal_design_', '');
                    var v = $('input[name="' + f + '"]').is(':checked');
                    var key = device === 'desktop' ? k : k + '_' + device;
                    settings.modal_design[key] = v;
                });
                
                var shortChecked = $('input[name="modal_design_show_desc"]').is(':checked');
                var longChecked  = $('input[name="modal_design_show_long_desc"]').is(':checked');
                var descKey     = device === 'desktop' ? 'show_desc'      : 'show_desc_'      + device;
                var descTypeKey = device === 'desktop' ? 'show_desc_type' : 'show_desc_type_' + device;
                if (longChecked) {
                    settings.modal_design[descKey]     = true;
                    settings.modal_design[descTypeKey] = 'long';
                } else if (shortChecked) {
                    settings.modal_design[descKey]     = true;
                    settings.modal_design[descTypeKey] = 'short';
                } else {
                    settings.modal_design[descKey]     = false;
                    settings.modal_design[descTypeKey] = 'short';
                }

                Object.keys(settings).forEach(function(k) {
                    if (k.startsWith('modal_design_') && k !== 'modal_design') delete settings[k];
                });
                delete settings._panel_subtab; 
            }

            if ($('input[name="checkout_design_preset"]').length) {
                settings.checkout_design = {
                    preset: $('input[name="checkout_design_preset"]').val() || 'classic',
                    colors: {
                        button: $('input[name="checkout_design_button"]').val() || ''+ImpC.surface2+'',
                        button_text: $('input[name="checkout_design_button_text"]').val() || '#ffffff',
                        text: $('input[name="checkout_design_text"]').val() || ''+ImpC.surface2+'',
                        form_bg: $('input[name="checkout_design_form_bg"]').val() || 'transparent',
                        field_bg: $('input[name="checkout_design_field_bg"]').val() || ''+ImpC.light+'',
                        field_border: $('input[name="checkout_design_field_border"]').val() || '#cccccc'
                    },
                    field_border_width: (function() { var v = parseInt($('input[name="checkout_design_field_border_width"]').val()); return isNaN(v) ? 1 : v; })(),
                    field_radius: (function() { var v = parseInt($('input[name="checkout_design_field_radius"]').val()); return isNaN(v) ? 10 : v; })(),
                    button_radius: (function() { var v = parseInt($('input[name="checkout_design_button_radius"]').val()); return isNaN(v) ? 10 : v; })(),
                    guest_checkout: $('input[name="checkout_design_guest_checkout"]').is(':checked'),
                    create_account: $('input[name="checkout_design_create_account"]').is(':checked'),
                    email_first: $('input[name="checkout_design_email_first"]').is(':checked'),
                    address_autocomplete: $('input[name="checkout_design_address_autocomplete"]').is(':checked'),
                    google_places_key: $('input[name="checkout_design_google_places_key"]').val() || '',
                    show_coupon: $('input[name="checkout_design_show_coupon"]').is(':checked'),
                    show_gift_card: $('input[name="checkout_design_show_gift_card"]').is(':checked'),
                    fields: JSON.parse($('input[name="checkout_design_fields"]').val() || '[]')
                };
                
                settings.checkout_design_button = settings.checkout_design.colors.button;
                settings.checkout_design_button_text = settings.checkout_design.colors.button_text;
                settings.checkout_design_text = settings.checkout_design.colors.text;
                settings.checkout_design_form_bg = settings.checkout_design.colors.form_bg;
                settings.checkout_design_field_bg = settings.checkout_design.colors.field_bg;
                settings.checkout_design_field_border = settings.checkout_design.colors.field_border;
                settings.checkout_design_field_border_width = settings.checkout_design.field_border_width;
                settings.checkout_design_field_radius = settings.checkout_design.field_radius;
                settings.checkout_design_button_radius = settings.checkout_design.button_radius;
            }

            if (settings.addons_json !== undefined) {
                try { settings.addons = JSON.parse(settings.addons_json || '[]'); } catch(e) { settings.addons = []; }
                delete settings.addons_json;
            }

            if (settings.configurator_json !== undefined) {
                try { settings.configurator = JSON.parse(settings.configurator_json || '[]'); } catch(e) { settings.configurator = []; }
                delete settings.configurator_json;
            }

            if (settings.cfg_sizes_json !== undefined) {
                try { settings.cfg_sizes = JSON.parse(settings.cfg_sizes_json || '[]'); } catch(e) { settings.cfg_sizes = []; }
                delete settings.cfg_sizes_json;
            }

            if (settings.cfg_groups_json !== undefined) {
                try { settings.cfg_groups = JSON.parse(settings.cfg_groups_json || '[]'); } catch(e) { settings.cfg_groups = []; }
                delete settings.cfg_groups_json;
            }

            return settings;
        }

        function showSaveStatus(saving) {
            var $status = $('#impulse-save-status');
            if (saving) {
                $status.removeClass('saved').addClass('saving').text('Saving...');
            } else {
                $status.removeClass('saving').addClass('saved').text('Saved');
            }
        }

        $('#impulse-page-name').on('click', function() {
            var $text = $(this);
            var $input = $('#impulse-page-name-input');
            var $ok = $('#impulse-page-name-ok');
            
            $text.hide();
            $input.val($text.text()).show().focus().select();
            $ok.show();
        });

        $('#impulse-page-name-ok').on('click', function() {
            savePageName();
        });

        $('#impulse-page-name-input').on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                savePageName();
            } else if (e.key === 'Escape') {
                cancelPageNameEdit();
            }
        });

        $('#impulse-page-name-input').on('input', function() {
            var newName = $(this).val().trim();
            var originalName = $('#impulse-page-name').text();
            if (newName !== originalName && newName) {
                $('#impulse-page-name-ok').show();
            } else {
                $('#impulse-page-name-ok').hide();
            }
        });
        
        function savePageName() {
            var $text = $('#impulse-page-name');
            var $input = $('#impulse-page-name-input');
            var $ok = $('#impulse-page-name-ok');
            var newName = $input.val().trim();
            
            if (!newName) {
                newName = $text.text(); 
            }
            
            $input.hide();
            $ok.hide();
            $text.text(newName).show();

            if (newName !== $text.data('original-name')) {
                
                var newSlug = newName.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
                
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ name: newName, slug: newSlug }),
                    success: function(resp) {
                        $text.data('original-name', newName);
                        var resolved = resp.slug || newSlug;
                        $('#impulse-page-slug-input').val(resolved);
                        Impulse.pageSlug = resolved;
                        
                        var $gc = $('.impulse-page-card[data-id="' + Impulse.pageId + '"]');
                        $gc.find('.name-text').text(newName);
                        $gc.find('.name-input').val(newName);
                        showSaveStatus();
                    }
                });
            }
        }
        
        function cancelPageNameEdit() {
            var $text = $('#impulse-page-name');
            var $input = $('#impulse-page-name-input');
            var $ok = $('#impulse-page-name-ok');
            
            $input.hide();
            $ok.hide();
            $text.show();
        }

        $('#impulse-slug-btn').on('click', function(e) {
            e.stopPropagation();
            var $modal = $('#impulse-slug-modal');
            if ($modal.is(':visible')) {
                $modal.hide();
            } else {
                $modal.show();
                $('#impulse-page-slug-input').focus().select();
            }
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('#impulse-slug-modal, #impulse-slug-btn').length) {
                $('#impulse-slug-modal').hide();
            }
        });

        

        
        
        $('#impulse-slug-copy').on('click', function() {
            var $btn = $(this);
            var slug = $('#impulse-page-slug-input').val();
            var prefix = ($('.impulse-slug-modal-prefix').text() || (window.Impulse.siteUrl.replace(/\/+$/, '') + '/'));
            var url = prefix + slug;
            
            navigator.clipboard.writeText(url).then(function() {
                $btn.addClass('copied');
                $btn.html('<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>');
                setTimeout(function() {
                    $btn.removeClass('copied');
                    $btn.html('<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>');
                }, 1500);
            });
        });

        $('#impulse-slug-ok').on('click', function() {
            var $input = $('#impulse-page-slug-input');
            var newSlug = $input.val().toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
            
            if (newSlug) {
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ slug: newSlug }),
                    success: function(resp) {
                        
                        if (resp.slug) $input.val(resp.slug);
                        $('#impulse-slug-modal').hide();
                    }
                });
            } else {
                $('#impulse-slug-modal').hide();
            }
        });

        var slugSaveTimer = null;
        $('#impulse-page-slug-input').on('input', function() {
            var $input = $(this);
            var newSlug = $input.val().toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
            
            clearTimeout(slugSaveTimer);
            slugSaveTimer = setTimeout(function() {
                if (newSlug) {
                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ slug: newSlug }),
                        success: function(resp) {
                            if (resp.slug) $input.val(resp.slug);
                        }
                    });
                }
            }, 500);
        });

        var draggedElement = null;
        var draggedTemplate = null;
        var lastDragPosition = { x: 0, y: 0 }; 

        var forbiddenInCells = ['section',  'rows', 'columns', 'slider', 'modal'];

        $(document).on('mousemove', '.impulse-block', function(e) {
            var rect = this.getBoundingClientRect();
            this.style.setProperty('--light-x', ((e.clientX - rect.left) / rect.width * 100) + '%');
            this.style.setProperty('--light-y', ((e.clientY - rect.top) / rect.height * 100) + '%');
        });

        
        $(document).on('click', '.impulse-block-pro', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if (window.triggerUpgradeCheckout) window.triggerUpgradeCheckout();
        });

        $(document).on('dragstart', '.impulse-block', function(e) {

            
            if ($(this).hasClass('impulse-block-pro')) {
                e.preventDefault();
                return false;
            }
            draggedElement = $(this).data('element');
            draggedTemplate = null;
            e.originalEvent.dataTransfer.setData('text/plain', draggedElement);
            e.originalEvent.dataTransfer.setData('element', draggedElement);
            e.originalEvent.dataTransfer.effectAllowed = 'copy';
            $(this).addClass('dragging');
            isDragActive = true; 
            
            $('.impulse-canvas').addClass('drag-active');
            
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ 
                    type: 'impulse-drag-start',
                    element: draggedElement,
                    template: null
                }, '*');
            }
        });
        
        $(document).on('dragend', '.impulse-block', function(e) {
            $(this).removeClass('dragging');
            $('.impulse-canvas').removeClass('drag-over drag-active');
            isDragActive = false; 
            if (pendingRefresh) {
                pendingRefresh = false;
                refreshPreview();
            }

            var element = draggedElement;
            var template = draggedTemplate;
            
            setTimeout(function() {
                
                if (!window._dropHandled && element && lastDragPosition.fromIframe) {
                    
                    var iframe = document.getElementById('impulse-iframe');
                    if (iframe && iframe.contentWindow) {
                        iframe.contentWindow.postMessage({ 
                            type: 'impulse-find-drop-at-position',
                            element: element,
                            template: template,
                            x: lastDragPosition.x,
                            y: lastDragPosition.y
                        }, '*');
                    }
                }
                window._dropHandled = false;

                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({ type: 'impulse-drag-end' }, '*');
                }
            }, 100);
            
            draggedElement = null;
            draggedTemplate = null;
            lastDragPosition = { x: 0, y: 0, fromIframe: false };
        });

        var $dropOverlay = $('#impulse-drop-overlay');
        
        $dropOverlay.on('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.originalEvent.dataTransfer.dropEffect = 'copy';

            

            
            
            var iframe = document.getElementById('impulse-iframe');
            var iframeRect = iframe.getBoundingClientRect();
            var _zoom = window._impulseFitScale || 1;
            var x = (e.clientX - iframeRect.left) / _zoom;
            var y = (e.clientY - iframeRect.top) / _zoom;

            lastDragPosition.x = x;
            lastDragPosition.y = y;
            lastDragPosition.fromIframe = true;

            if (iframe.contentWindow) {
                iframe.contentWindow.postMessage({
                    type: 'impulse-highlight-target',
                    x: x,
                    y: y
                }, '*');
            }
        });
        
        $dropOverlay.on('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var iframe = document.getElementById('impulse-iframe');
            var iframeRect = iframe.getBoundingClientRect();
            var _zoom = window._impulseFitScale || 1;
            var x = (e.clientX - iframeRect.left) / _zoom;
            var y = (e.clientY - iframeRect.top) / _zoom;

            
            if (iframe.contentWindow && (draggedElement || draggedTemplate)) {
                iframe.contentWindow.postMessage({
                    type: 'impulse-find-drop-at-position',
                    element: draggedElement,
                    template: draggedTemplate,
                    x: x,
                    y: y
                }, '*');
            }

            window._dropHandled = true;
            $('.impulse-canvas').removeClass('drag-active');
            if (iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-drag-end' }, '*');
            }
        });
        
        $dropOverlay.on('dragleave', function(e) {
            
        });

        
        $(document).on('click', '.impulse-block:not(.impulse-shape-item)', function(e) {

            if (isDragActive) {
                isDragActive = false;
                $('.impulse-block').removeClass('dragging');
                $('.impulse-canvas').removeClass('drag-over drag-active');
            }
            var elementType = $(this).attr('data-element');
            if (!elementType) return;
            
            var debug = window.impulseDebug || false;
            if (debug) console.log('[block-click] type:', elementType, 'pageId:', Impulse.pageId);

            if (!Impulse.pageId) {
                console.warn('Cannot add element: no page is open');
                return;
            }
            
            var parentId = null;
            var position = null;
            var cellGridData = null;
            var addAfterSibling = null;

            if (elementType === 'header') {
                if (debug) console.log('[block-click] adding header at top');
                addElementWithSettings(elementType, {}, null, 0);
                return;
            }

            if (elementType === 'footer') {
                if (debug) console.log('[block-click] adding footer at end');
                addElementWithSettings(elementType, { _force_end: true }, null, 999999);
                return;
            }

            var footerElement = null;
            try {
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentDocument) {
                    footerElement = iframe.contentDocument.querySelector('.impulse-el[data-type="footer"]');
                }
            } catch(err) {}

            var containerTypes = ['section',  'rows', 'columns', 'slider', 'modal'];
            
            var rootOnlyTypes = ['modal'];
            
            if (debug) console.log('[block-click] selection state:', {
                selectedElementId: selectedElementId,
                selectedElementType: selectedElementType,
                selectedGridParentId: selectedGridParentId,
                selectedCellGridParentId: selectedCellGridParentId,
                selectedCellGridCellKey: selectedCellGridCellKey,
                hasFooter: !!footerElement
            });

            if (selectedCellGridParentId && selectedCellGridCellKey) {
                
                if (forbiddenInCells.indexOf(elementType) !== -1) {
                    if (debug) console.log('[block-click] prevented', elementType, 'inside rows/columns');
                    return;
                }
                
                var parts = selectedCellGridCellKey.split('-');

                var cellRow, cellCol;
                if (selectedElementType === 'columns') {
                    cellCol = parseInt(parts[0]); 
                    cellRow = parseInt(parts[1]); 
                } else {
                    cellRow = parseInt(parts[0]);
                    cellCol = parseInt(parts[1]);
                }
                parentId = selectedCellGridParentId;
                cellGridData = { row: cellRow, col: cellCol };
                if (debug) console.log('[block-click] adding to cell:', cellRow, cellCol);
            }
            
            else if (selectedGridParentId) {
                
                if (forbiddenInCells.indexOf(elementType) !== -1) {
                    if (debug) console.log('[block-click] prevented', elementType, 'inside grid');
                    return;
                }
                
                parentId = selectedGridParentId;
                if (selectedGridCellIndex !== null && selectedGridCellIndex !== undefined && !isNaN(selectedGridCellIndex)) {
                    position = selectedGridCellIndex;
                }
                if (debug) console.log('[block-click] adding to grid parent:', parentId, 'position:', position);
            }
            
            else if (selectedElementId && selectedElementType) {
                if (containerTypes.indexOf(selectedElementType) !== -1) {
                    
                    if (rootOnlyTypes.indexOf(elementType) !== -1) {
                        if (debug) console.log('[block-click] prevented root-only', elementType, 'inside', selectedElementType);
                        return;
                    }
                    
                    if (elementType === 'section' && selectedElementType === 'section') {
                        var _smActive = Impulse.pageSettings && (true);
                        var _parentIsScreen = false;
                        if (_smActive) {
                            try {
                                var _ifrDoc = document.getElementById('impulse-iframe').contentDocument;
                                var _selEl = _ifrDoc && _ifrDoc.querySelector('.impulse-el[data-id="' + selectedElementId + '"]');
                                _parentIsScreen = !!(_selEl && _selEl.parentElement && _selEl.parentElement.classList.contains('impulse-content-wrapper'));
                            } catch(e) {}
                        }
                        if (!_parentIsScreen) {
                            if (debug) console.log('[block-click] prevented section inside section');
                            return;
                        }
                        if (debug) console.log('[block-click] section inside screen — allowed');
                    }
                    
                    if (elementType === 'slider' && selectedElementType === 'slider') {
                        if (debug) console.log('[block-click] prevented slider inside slider');
                        return;
                    }
                    
                    if ((selectedElementType === 'rows' || selectedElementType === 'columns' || selectedElementType === 'grid') && 
                        forbiddenInCells.indexOf(elementType) !== -1) {
                        if (debug) console.log('[block-click] prevented', elementType, 'inside', selectedElementType);
                        return;
                    }
                    
                    parentId = selectedElementId;
                    if (debug) console.log('[block-click] adding inside container:', selectedElementType);
                } else {
                    
                    addAfterSibling = selectedElementId;
                    if (debug) console.log('[block-click] adding after sibling:', selectedElementId);
                }
            }
            
            else {

                
                var isScreenModeActive = Impulse.pageSettings && ((Impulse.pageSettings.body_scroll || 'snap') !== 'classic');
                if (isScreenModeActive && rootOnlyTypes.indexOf(elementType) === -1 && elementType !== 'section') {
                    var activeScreenSectionId = null;
                    try {
                        var _scIframe = document.getElementById('impulse-iframe');
                        var _scIdx = window._savedScreenIndex || 0;
                        if (_scIframe && _scIframe.contentWindow && _scIframe.contentWindow.impulseScreenMode && typeof _scIframe.contentWindow.impulseScreenMode.getCurrentScreen === 'function') {
                            _scIdx = _scIframe.contentWindow.impulseScreenMode.getCurrentScreen();
                        }
                        var _scSections = _scIframe.contentDocument.querySelectorAll('.impulse-content-wrapper > .impulse-el[data-type="section"]');
                        if (_scSections[_scIdx]) {
                            activeScreenSectionId = _scSections[_scIdx].getAttribute('data-id');
                        }
                    } catch(ex) {}
                    if (activeScreenSectionId) {
                        
                        var _sliderInScreen = null;
                        try {
                            var _activeSec = _scIframe.contentDocument.querySelector('.impulse-el[data-id="' + activeScreenSectionId + '"]');
                            if (_activeSec) {
                                var _sliders = _activeSec.querySelectorAll('.impulse-el[data-type="slider"]');
                                if (_sliders.length === 1) _sliderInScreen = _sliders[0];
                            }
                        } catch(_se) {}
                        if (_sliderInScreen) {
                            var _sId = parseInt(_sliderInScreen.dataset.id) || 0;
                            var _sCarousel = _sliderInScreen.querySelector('.impulse-new-slider');
                            var _sSlideIdx = _sCarousel ? (parseInt(_sCarousel.dataset.currentSlide) || 0) : 0;
                            var _sCurSlideInput = $('input[name="current_slide"]');
                            if (_sCurSlideInput.length) _sSlideIdx = parseInt(_sCurSlideInput.val()) || _sSlideIdx;
                            if (debug) console.log('[block-click] routing to slider in screen:', _sId, 'slide:', _sSlideIdx);
                            addElementWithSettings(elementType, { slide_index: _sSlideIdx }, _sId, position);
                            return;
                        }
                        parentId = activeScreenSectionId;
                        if (debug) console.log('[block-click] screen mode: adding inside active screen section:', parentId);
                    } else {
                        if (debug) console.log('[block-click] screen mode: no active screen id found, falling back to root');
                    }
                } else if (footerElement) {
                    var footerId = footerElement.getAttribute('data-id');
                    if (footerId) {
                        if (debug) console.log('[block-click] adding before footer:', footerId);
                        addElementNearSibling(elementType, parseInt(footerId), 'before');
                        return;
                    }
                } else {
                    if (debug) console.log('[block-click] adding to page root');
                }
            }

            
            
            var _panelType = $('.impulse-panel-right').data('element-type');
            var _panelId   = parseInt($('.impulse-panel-right').data('element-id')) || 0;
            if ((_panelType === 'slider' || _panelType === 'carousel' || selectedElementType === 'slider' || selectedElementType === 'carousel') && (_panelId || parentId)) {
                var _sliderId = _panelId || parentId;
                var currentSlideIndex = parseInt($('input[name="current_slide"]').val()) || 0;
                if (debug) console.log('[block-click] adding to carousel/slider, slide:', currentSlideIndex);
                addElementWithSettings(elementType, { slide_index: currentSlideIndex }, _sliderId, position);
            } else if (addAfterSibling) {
                
                addElementNearSibling(elementType, addAfterSibling, 'after');
            } else {
                if (debug) console.log('[block-click] calling addElement:', elementType, parentId, position);
                addElement(elementType, parentId, position, null, cellGridData);
            }
        });

        $('.impulse-canvas').on('dragover', function(e) {
            e.preventDefault();
            $(this).addClass('drag-over');
        });
        
        $('.impulse-canvas').on('dragleave', function(e) {
            var rect = this.getBoundingClientRect();
            var x = e.originalEvent.clientX;
            var y = e.originalEvent.clientY;
            if (x < rect.left || x >= rect.right || y < rect.top || y >= rect.bottom) {
                $(this).removeClass('drag-over');
            }
        });
        
        $('.impulse-canvas').on('drop', function(e) {
            e.preventDefault();
            $(this).removeClass('drag-over drag-active');
            
        });

        $('.impulse-preview-area, .impulse-canvas').on('click', function(e) {
            
            var $t = $(e.target);
            if ($t.is('.impulse-preview-area, .impulse-canvas-scroll, .impulse-canvas') ||
                $t.is('#impulse-load-bar, .impulse-canvas-zoom-badge')) {
                deselectElement();
                if (document.activeElement && document.activeElement !== document.body) {
                    document.activeElement.blur();
                }
                
                showPageSettings();
            }
        });

        var skipNextCellGridSelect = false; 
        
        var _impulseDepthDeadHandled = false;
        window.addEventListener('message', function(e) {
            if (!e.data || !e.data.type) return;

            if (e.data.type === 'impulse-quickview-closed') {
                return; 
            }

            

            

            

            

            
            if (e.data.type === 'impulse-depth-image-dead') {
                if (_impulseDepthDeadHandled) return; 
                _impulseDepthDeadHandled = true;
                try {
                    var _deadUrl = (e.data.url || '') + '';
                    var _isLocalUrl = _deadUrl.indexOf('/storage/') === 0
                        || _deadUrl.indexOf('/wp-content/') === 0
                        || _deadUrl.indexOf(location.origin + '/storage/') === 0
                        || _deadUrl.indexOf(location.origin + '/wp-content/') === 0;
                    if (_isLocalUrl) {
                        if (typeof showToast === 'function') {
                            showToast('3D background failed to load. Check the file in your media library.', 'error');
                        }
                        return; 
                    }

                    
                    
                    if (Impulse.pageSettings) {
                        Impulse.pageSettings.screen_depth_image  = '';
                        Impulse.pageSettings.screen_depth_map    = '';
                        Impulse.pageSettings.screen_depth_enabled = '0';
                        if (Impulse.pageSettings.screen_cloud_effect === 'depth_image') {
                            Impulse.pageSettings.screen_cloud_effect = 'none';
                        }
                        if (typeof saveScreenBarSettings === 'function') saveScreenBarSettings(false);
                        if (typeof showToast === 'function') showToast('3D image no longer available on Platform — cleared from this page.', 'info');
                    }
                } catch (ex) {}
                return;
            }

            if (e.data.type === 'impulse-select') {
                
                if ((e.data.elementType === 'rows' || e.data.elementType === 'columns') && skipNextCellGridSelect && !e.data.fromSelectParent) {
                    skipNextCellGridSelect = false;
                    return;
                }
                
                if (e.data.elementType === 'grid' && skipNextGridCellSelect) {
                    skipNextGridCellSelect = false;
                    return;
                }
                
                if (e.data.elementType === 'grid') {
                    selectedGridCellIndex = null;
                }

                

                openSettings(e.data.id, e.data.elementType);

                

                

                if (!e.data.fromDrag) scrollToElementInIframe(e.data.id);

                

                
                if (typeof syncStructureSelection === 'function') {
                    setTimeout(syncStructureSelection, 0);
                } else {
                    $('.impulse-structure-item').removeClass('selected');
                    $('.impulse-structure-item[data-id="' + e.data.id + '"]').addClass('selected');
                }
                
                if (e.data.elementType === 'section') {
                    $('.impulse-structure-item').removeClass('screen-current');
                    $('.impulse-structure-item[data-id="' + e.data.id + '"]').addClass('screen-current');
                    $('.impulse-srow').removeClass('active');
                    $('.impulse-srow[data-id="' + e.data.id + '"]').addClass('active');
                }
            }

            

            

            if (e.data.type === 'impulse-cell-select') {
                var _csParent = e.data.parentId;
                var _csType   = e.data.parentType;
                var _csKey    = e.data.cellKey;
                if (!_csParent || !_csType || _csKey === undefined || _csKey === null || _csKey === '') return;
                if (_csType === 'grid') {
                    selectedGridParentId = _csParent;
                    selectedGridCellIndex = parseInt(_csKey, 10);
                    selectedCellGridParentId = null;
                    selectedCellGridCellKey = null;
                    skipNextGridCellSelect = true; 
                    openSettings(_csParent, 'grid');
                    setTimeout(function() {
                        var existing = $('.impulse-panel-right').data('existing-settings') || {};
                        var panelSettings = collectSettingsFromPanel();
                        var mergedSettings = Object.assign({}, existing, panelSettings);
                        $('.impulse-panel-right').data('existing-settings', mergedSettings);
                        var html = buildSettingsForm('grid', mergedSettings, []);
                        $('#impulse-settings-body').html(html);
                    }, 100);
                } else {
                    
                    selectedCellGridParentId = _csParent;
                    selectedCellGridCellKey = String(_csKey);
                    selectedGridParentId = null;
                    selectedGridCellIndex = null;
                    skipNextCellGridSelect = true; 
                    openSettings(_csParent, _csType);
                    setTimeout(function() {
                        $('input[name="_selected_cells"]').val(JSON.stringify([_csKey]));
                        var existing = $('.impulse-panel-right').data('existing-settings') || {};
                        rebuildCellGridEditorPanel(_csParent, existing, [_csKey]);
                    }, 100);
                }
                
                $('.impulse-structure-item').removeClass('selected');
                $('.impulse-structure-item[data-parent-id="' + _csParent + '"][data-cell="' + _csKey + '"]').addClass('selected');
                return;
            }

            
            
            if (e.data.type === 'impulse-multi-select') {
                window._impMultiSel = Array.isArray(e.data.ids) ? e.data.ids.slice() : [];
                if (!window._impMultiSel.length) window._impMultiParent = null;
                impApplyMultiSelHighlight();
            }

            if (e.data.type === 'impulse-deselect') {
                
                var _isScreenMode = Impulse.pageSettings && (true);
                if (_isScreenMode) {
                    var screenId = null;
                    try {
                        var _dsIframe = document.getElementById('impulse-iframe');
                        var _dsIdx = window._savedScreenIndex || 0;
                        if (_dsIframe && _dsIframe.contentWindow && _dsIframe.contentWindow.impulseScreenMode && typeof _dsIframe.contentWindow.impulseScreenMode.getCurrentScreen === 'function') {
                            _dsIdx = _dsIframe.contentWindow.impulseScreenMode.getCurrentScreen();
                        }
                        var _dsSections = _dsIframe.contentDocument.querySelectorAll('.impulse-content-wrapper > .impulse-el[data-type="section"]');
                        if (_dsSections[_dsIdx]) {
                            screenId = _dsSections[_dsIdx].getAttribute('data-id');
                        }
                    } catch(ex) {}
                    if (screenId) {
                        selectedElementId = screenId;
                        selectedElementType = 'section';
                        selectedGridParentId = null;
                        selectedGridCellIndex = null;
                        selectedCellGridParentId = null;
                        selectedCellGridCellKey = null;
                        openSettings(screenId, 'section');
                        return;
                    }
                }
                selectedElementId = null;
                selectedElementType = null;
                selectedGridParentId = null;
                selectedGridCellIndex = null;
                selectedCellGridParentId = null;
                selectedCellGridCellKey = null;
                showPageSettings();
            }
            
            if (e.data.type === 'impulse-goto-seo-site') {
                switchWorkspace('settings');
            }

            if (e.data.type === 'impulse-goto-products') {

                

                

                

                

                

                window.Impulse = window.Impulse || {};
                window.Impulse._storeSectionOverride = 'products';
                switchWorkspace('store');
                setTimeout(function() {
                    
                    if (typeof switchStoreSection === 'function') {
                        switchStoreSection('products');
                    }
                    
                    $(document).trigger('impulse:products:show');

                    
                    
                    setTimeout(function() {
                        $(document).trigger('impulse:products:open-new');
                    }, 150);
                }, 80);
            }

            if (e.data.type === 'impulse-goto-add-service') {
                switchWorkspace('store');

                setTimeout(function() {
                    if (typeof switchStoreSection === 'function') {
                        switchStoreSection('bookings');
                    }
                    setTimeout(function() {
                        var addBtn = document.getElementById('topbar-add-service');
                        if (addBtn) addBtn.click();
                    }, 50);
                }, 50);
            }

            if (e.data.type === 'impulse-page-height') {
                
                var _canvas = document.querySelector('.impulse-canvas');
                if (!(_canvas && _canvas.dataset.screenMode === '1')) {
                    var _iframeEl = document.getElementById('impulse-iframe');
                    if (_iframeEl && e.data.height) {

                        

                        

                        
                        var _vp = window.innerHeight || document.documentElement.clientHeight || 0;
                        var _device = _canvas ? _canvas.getAttribute('data-device') : 'desktop';
                        var _target;
                        if (_device === 'mobile') {
                            _target = Math.round(375 * 16 / 9); 
                        } else if (_device === 'tablet') {
                            _target = Math.round(768 * 4 / 3); 
                        } else {
                            _target = Math.max(200, _vp - 104);
                        }
                        
                        _target = Math.min(_target, Math.max(200, _vp - 104));
                        var _curr = parseInt(_iframeEl.style.height, 10) || 0;
                        if (Math.abs(_curr - _target) > 2) {
                            _iframeEl.style.height = _target + 'px';
                        }
                    }
                }
            }

            if (e.data.type === 'impulse-screen-change') {
                var idx = e.data.screenIndex;

                

                

                var _isInitFire = !!e.data.isInit;
                window._savedScreenIndex = idx;
                
                $('.impulse-srow').removeClass('active');
                $('.impulse-srow[data-screen-index="' + idx + '"]').addClass('active');
                var screenId = null;
                var screenEl = null;
                try {
                    var _scIframe = document.getElementById('impulse-iframe');
                    var _scSections = _scIframe.contentDocument.querySelectorAll('.impulse-content-wrapper > .impulse-el[data-type="section"]');
                    if (_scSections[idx]) { screenId = _scSections[idx].getAttribute('data-id'); screenEl = _scSections[idx]; }
                } catch(ex) {}
                $('.impulse-structure-item').removeClass('screen-current');
                if (screenId) {
                    $('.impulse-structure-item[data-id="' + screenId + '"]').addClass('screen-current');

                    

                    
                    var _screenChangeSkip = (selectedElementType === 'carousel' || selectedElementType === 'slider');

                    if (!_isInitFire && !_screenChangeSkip && selectedElementId && selectedElementType !== 'section') {
                        try {
                            var _scSel = _scIframe.contentDocument.querySelector('.impulse-el[data-id="' + selectedElementId + '"]');
                            var _onCurrent   = _scSel && _scSections[idx] && _scSections[idx].contains(_scSel);
                            if (_scSel && !_onCurrent) {

                                

                                selectedElementId = null;
                                selectedElementType = null;
                                selectedGridParentId = null;
                                selectedGridCellIndex = null;
                                selectedCellGridParentId = null;
                                selectedCellGridCellKey = null;
                                try {
                                    _scIframe.contentDocument.querySelectorAll('.impulse-el.selected').forEach(function(el) {
                                        el.classList.remove('selected');
                                    });
                                } catch(_e) {}
                                $('.impulse-panel-right').removeData('element-id').removeAttr('data-element-id');
                                var _psSwitch = Impulse.pageSettings || {};
                                var _isPureScene = (true);
                                if (_isPureScene && typeof _showCurrentScreenSettings === 'function') {
                                    _showCurrentScreenSettings();
                                } else if (typeof showPageSettings === 'function') {
                                    showPageSettings();
                                }
                                
                                return;
                            }
                        } catch(_ex) {}
                    }
                    
                    selectedElementId = screenId;
                    selectedElementType = 'section';
                    selectedGridParentId = null;
                    selectedGridCellIndex = null;
                    selectedCellGridParentId = null;
                    selectedCellGridCellKey = null;
                }

                
                if (typeof window.populateEnvPresets === 'function') {
                    if (window._envBarScreenId !== screenId) {
                        window._envBarScreenId = screenId;
                        _loadScreenEnvIntoBar(screenEl);
                    }
                }
            }
            
            if (e.data.type === 'impulse-grid-cell-select') {
                
                selectedGridParentId = e.data.parentId;
                var rawCellIndex = e.data.cellIndex;
                if (rawCellIndex !== null && rawCellIndex !== undefined) {
                    var parsed = parseInt(rawCellIndex, 10);
                    selectedGridCellIndex = isNaN(parsed) ? null : parsed;
                } else {
                    selectedGridCellIndex = null;
                }

                

                

                
                var panelElementId = $('.impulse-panel-right').data('element-id');
                var _gridAlreadyOpen = selectedElementType === 'grid' && panelElementId == e.data.parentId;
                if (_gridAlreadyOpen) {
                    skipNextGridCellSelect = true;
                    setTimeout(function() { skipNextGridCellSelect = false; }, 100);
                    
                    var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                    var panelSettings = collectSettingsFromPanel();
                    var mergedSettings = Object.assign({}, existingSettings, panelSettings);
                    $('.impulse-panel-right').data('existing-settings', mergedSettings);

                    
                    var html = buildSettingsForm('grid', mergedSettings, []);
                    $('#impulse-settings-body').html(html);
                }
                updateStructureTree();
            }
            
            if (e.data.type === 'impulse-rows-select') {
                
                skipNextCellGridSelect = true;
                setTimeout(function() { skipNextCellGridSelect = false; }, 100);

                var cellKey = e.data.cellKey; 
                var shiftKey = e.data.shiftKey || false;
                var parentElementType = e.data.elementType || 'rows'; 
                
                selectedCellGridParentId = e.data.parentId;
                selectedCellGridCellKey = cellKey;

                selectedGridParentId = null;
                selectedGridCellIndex = null;
                
                var elementId = e.data.parentId;
                if (!elementId) return;
                
                var panelElementId = $('.impulse-panel-right').data('element-id');

                var cellClass = parentElementType === 'columns' ? '.impulse-layout-cell' : '.impulse-rows-cell';
                var dataKey = parentElementType === 'columns' ? 'columns' : 'rows';

                if ((selectedElementType === 'rows' || selectedElementType === 'columns') && panelElementId == elementId) {
                    var currentSelection = [];
                    try {
                        currentSelection = JSON.parse($('input[name="_selected_cells"]').val() || '[]');
                    } catch(ex) {}
                    
                    var newSelection;
                    var idx = currentSelection.indexOf(cellKey);
                    
                    if (shiftKey) {
                        if (idx > -1) {
                            currentSelection.splice(idx, 1);
                            newSelection = currentSelection;
                        } else {
                            newSelection = currentSelection.concat([cellKey]);
                        }
                    } else {
                        if (currentSelection.length === 1 && idx > -1) {
                            newSelection = [];
                        } else {
                            newSelection = [cellKey];
                        }
                    }
                    
                    $('input[name="_selected_cells"]').val(JSON.stringify(newSelection));
                    
                    var currentSettings = gatherFormSettings();
                    currentSettings._selected_cells = newSelection;
                    rebuildCellGridPanel(elementId, currentSettings);

                    try {
                        var iframe = document.getElementById('impulse-iframe');
                        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        iframeDoc.querySelectorAll(cellClass).forEach(function(c) { 
                            c.classList.remove('selected'); 
                        });
                        newSelection.forEach(function(key) {
                            var parts = key.split('-');
                            var cell;
                            if (parentElementType === 'columns') {
                                cell = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"] .impulse-layout-cell[data-col="' + parts[0] + '"][data-row="' + parts[1] + '"]');
                            } else {
                                cell = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"] .impulse-rows-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]');
                            }
                            if (cell) cell.classList.add('selected');
                        });
                    } catch(ex) {}
                } else {
                    var cached = getCachedCellGridSettings(elementId);
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + elementId,
                        method: 'GET',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function(resp) {
                            var existingSettings = resp.settings || {};
                            
                            if (typeof existingSettings[dataKey] === 'string') {
                                try { existingSettings[dataKey] = JSON.parse(existingSettings[dataKey]); } catch(e) {}
                            }
                            if (typeof existingSettings.rows === 'string') {
                                try { existingSettings.rows = JSON.parse(existingSettings.rows); } catch(e) {}
                            }
                            if (typeof existingSettings.columns === 'string') {
                                try { existingSettings.columns = JSON.parse(existingSettings.columns); } catch(e) {}
                            }
                            
                            if (cached) {
                                existingSettings = $.extend({}, existingSettings, cached);
                            }
                            
                            existingSettings._selected_cells = [cellKey];
                            
                            var settingsToSave = $.extend({}, existingSettings);
                            if (Array.isArray(settingsToSave.rows)) {
                                settingsToSave.rows = JSON.stringify(settingsToSave.rows);
                            }
                            if (Array.isArray(settingsToSave.columns)) {
                                settingsToSave.columns = JSON.stringify(settingsToSave.columns);
                            }
                            if (Array.isArray(settingsToSave._selected_cells)) {
                                settingsToSave._selected_cells = JSON.stringify(settingsToSave._selected_cells);
                            }
                            
                            $.ajax({
                                url: Impulse.api + 'elements/' + elementId,
                                method: 'PUT',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify({ settings: settingsToSave, page_id: Impulse.pageId }),
                                async: false,
                                success: function() {
                                    updateCellGridCache(elementId, existingSettings);
                                    openSettings(elementId, parentElementType);
                                }
                            });
                        }
                    });
                }
                updateStructureTree();
            }

            function gatherFormSettings() {
                var settings = {};
                $('.impulse-panel-right input, .impulse-panel-right select, .impulse-panel-right textarea').each(function() {
                    var name = $(this).attr('name');
                    if (!name) return;
                    if ($(this).is(':checkbox')) {
                        settings[name] = $(this).is(':checked');
                    } else {
                        settings[name] = $(this).val();
                    }
                });
                return settings;
            }

            function rebuildCellGridPanel(elementId, settings) {
                
                if (typeof settings.rows === 'string') {
                    try { settings.rows = JSON.parse(settings.rows); } catch(e) {}
                }
                if (typeof settings.columns === 'string') {
                    try { settings.columns = JSON.parse(settings.columns); } catch(e) {}
                }
                if (typeof settings._selected_cells === 'string') {
                    try { settings._selected_cells = JSON.parse(settings._selected_cells); } catch(e) {}
                }

                var elType = selectedElementType === 'columns' ? 'columns' : 'rows';
                
                updateCellGridCache(elementId, settings);
                $('.impulse-panel-right').data('existing-settings', settings);
                var children = $('.impulse-panel-right').data('cell-grid-children') || [];
                
                var html = buildSettingsForm(elType, settings, children);
                $('#impulse-settings-body').html(html);
                $('.impulse-panel-right').data('element-id', elementId);
                $('.impulse-panel-right').data('element-type', elType);
                selectedElementType = elType;
                window.impulseFlipEditingSide = 'front';
                initGridSelectorFromRows();
                updateGridSelectorVisual();

                if (window._pendingContentChange && window._pendingContentChange.id == elementId) {
                    var _pc = window._pendingContentChange;
                    window._pendingContentChange = null;
                    var $f = $('[name="' + _pc.field + '"]');
                    if ($f.length) $f.val(_pc.value);
                    var $ed = $('.impulse-richtext-editor[data-name="' + _pc.field + '"]');
                    if ($ed.length) $ed.html(_pc.value);
                    var _ex = $('.impulse-panel-right').data('existing-settings') || {};
                    _ex[_pc.field] = _pc.value;
                    $('.impulse-panel-right').data('existing-settings', _ex);
                }

                livePreviewSettings(elementId, elType);
            }

            if (e.data.type === 'impulse-rows-row-widths') {
                var elementId = e.data.parentId;
                var rowIndex = e.data.rowIndex;
                var newWidths = e.data.widths;
                
                if (elementId && newWidths && newWidths.length > 0) {
                    
                    var cached = getCachedCellGridSettings(elementId);
                    
                    var updateWidths = function(currentSettings) {
                        var rows = currentSettings.rows || [];
                        if (typeof rows === 'string') {
                            try { rows = JSON.parse(rows); } catch(e) { rows = []; }
                        }
                        if (rows[rowIndex]) {
                            rows[rowIndex].widths = newWidths;

                            var newSettings = $.extend({}, currentSettings, { rows: rows });
                            updateCellGridCache(elementId, newSettings);

                            $.ajax({
                                url: Impulse.api + 'elements/' + elementId,
                                method: 'PUT',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify({ settings: newSettings, page_id: Impulse.pageId }),
                                async: false
                            });

                            if ((selectedElementType === 'rows' || selectedElementType === 'columns') && selectedElementId == elementId) {
                                $('input[name="rows"]').val(JSON.stringify(rows));
                            }
                        }
                    };
                    
                    if (cached) {
                        updateWidths(cached);
                    } else {
                        $.ajax({
                            url: Impulse.api + 'elements/' + elementId,
                            method: 'GET',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            async: false,
                            success: function(resp) {
                                if (resp && resp.settings) {
                                    updateWidths(resp.settings);
                                }
                            }
                        });
                    }
                }
            }
            
            if (e.data.type === 'impulse-drop') {
                window._dropHandled = true; 

                
                
                var _dropElType = e.data.element || '';
                try {
                    if (_dropElType && _dropElType.startsWith && _dropElType.startsWith('{')) {
                        var _parsed = JSON.parse(_dropElType);
                        if (_parsed.type === 'user-template') _dropElType = _parsed.elementType || '';
                    }
                } catch(_ex) {}

                

                

                if (_dropElType === 'header') {
                    addElementWithSettings('header', {}, null, 0);
                    return;
                }
                if (_dropElType === 'footer') {
                    addElementWithSettings('footer', { _force_end: true }, null, 999999);
                    return;
                }

                if ((Impulse.pageSettings && (true))) {
                    var dropElementType = e.data.element || '';
                    try {
                        var parsed = JSON.parse(dropElementType);
                        if (parsed.type === 'user-template') dropElementType = parsed.elementType || '';
                    } catch(ex) {}
                    var _rootOverlayTypes = ['section', 'header', 'footer', 'modal'];
                    if (_rootOverlayTypes.indexOf(dropElementType) === -1 &&
                        (!e.data.parentId || e.data.parentId === 0 || e.data.parentId === '0') &&
                        !e.data.tabIndex && e.data.tabIndex !== 0 &&
                        !e.data.slideIndex && e.data.slideIndex !== 0 &&
                        !e.data.cellGridData && !e.data.gridCellIndex && e.data.gridCellIndex !== 0 &&
                        !e.data.insertBeforeId && !e.data.insertAfterId) {
                        var screenId = getActiveScreenId();
                        if (screenId) {
                            e.data.parentId = screenId;
                        } else {
                            return;
                        }
                    }
                }

                var userTemplate = null;
                try {
                    if (e.data.element && e.data.element.startsWith('{')) {
                        var parsed = JSON.parse(e.data.element);
                        if (parsed.type === 'user-template') {
                            userTemplate = parsed;
                        }
                    }
                } catch(ex) {}

                

                
                if (e.data.element && e.data.element.startsWith('shape:')) {
                    var shapeData = window._draggedShapeData;
                    if (shapeData && typeof window.addLibraryShapeToBg === 'function') {
                        window.addLibraryShapeToBg(shapeData, false);
                    }
                    window._draggedShapeData = null;
                    return;
                }

                if (e.data.element && e.data.element.startsWith('graphic:')) {
                    var graphicData = window._draggedGraphicData;
                    if (graphicData && typeof window.addLibraryShapeToBg === 'function') {
                        downloadGraphicLocal(graphicData.image_url, function(localUrl) {
                            window.addLibraryShapeToBg({ name: graphicData.name, image_url: localUrl }, true);
                        });
                    }
                    window._draggedGraphicData = null;
                    return;
                }

                if (e.data.element && e.data.element.startsWith('media:')) {
                    var mediaData = window._draggedMediaData;
                    if (mediaData) {
                        var dropParentIdM = (e.data.parentId !== undefined && e.data.parentId !== null) ? e.data.parentId : (selectedElementId || null);
                        addElementWithSettings('image', {
                            image_id: mediaData.id,
                            width: 50,
                            alt: mediaData.title || mediaData.filename || ''
                        }, dropParentIdM, -1);
                        window._draggedMediaData = null;
                    }
                    return;
                }

                var dropType = userTemplate ? (userTemplate.elementType || '') : (e.data.element || '');
                var dropParentType = e.data.parentType || '';
                if (dropParentType) {
                    var layoutCells = [ 'rows', 'columns'];
                    var cellForbidden = ['section',  'rows', 'columns', 'slider', 'modal'];
                    
                    if (dropType === 'modal') return;
                    
                    if (dropType === 'section' && dropParentType === 'section' && !e.data.parentIsScreen) return;
                    
                    if (dropType === 'slider' && dropParentType === 'slider') return;
                    
                    if (layoutCells.indexOf(dropParentType) !== -1 && cellForbidden.indexOf(dropType) !== -1) return;
                }

                if (e.data.tabIndex !== null && e.data.tabIndex !== undefined) {
                    var extraSettings = { tab_index: e.data.tabIndex };
                    if (userTemplate) {
                        var mergedSettings = $.extend({}, userTemplate.settings, extraSettings);
                        addElementWithSettings(userTemplate.elementType, mergedSettings, e.data.parentId, e.data.position, templateChildrenCallback(userTemplate.children));
                    } else {
                        addElementWithSettings(e.data.element, extraSettings, e.data.parentId, e.data.position);
                    }
                }
                
                else if (e.data.slideIndex !== null && e.data.slideIndex !== undefined) {
                    var extraSettings = { slide_index: e.data.slideIndex };
                    if (userTemplate) {
                        var mergedSettings = $.extend({}, userTemplate.settings, extraSettings);
                        addElementWithSettings(userTemplate.elementType, mergedSettings, e.data.parentId, e.data.position, templateChildrenCallback(userTemplate.children));
                    } else {
                        addElementWithSettings(e.data.element, extraSettings, e.data.parentId, e.data.position);
                    }
                }
                
                else if (e.data.insertBeforeId || e.data.insertAfterId) {
                    var siblingId = e.data.insertBeforeId || e.data.insertAfterId;
                    var position = e.data.insertBeforeId ? 'before' : 'after';

                    if (userTemplate) {
                        addElementWithSettingsNearSibling(userTemplate.elementType, userTemplate.settings, siblingId, position, templateChildrenCallback(userTemplate.children));
                    } else {
                        
                        addElementNearSibling(e.data.element, siblingId, position);
                    }
                } else if (e.data.cellGridData) {
                    
                    var droppedType = e.data.element;
                    if (userTemplate) {
                        droppedType = userTemplate.elementType;
                    }
                    if (forbiddenInCells.indexOf(droppedType) !== -1) {
                        return;
                    }

                    if (userTemplate) {
                        addElementWithSettingsToCellGridCell(userTemplate.elementType, userTemplate.settings, e.data.parentId, e.data.cellGridData.row, e.data.cellGridData.col, templateChildrenCallback(userTemplate.children));
                    } else {
                        addElementToCellGridCell(e.data.element, e.data.parentId, e.data.cellGridData.row, e.data.cellGridData.col);
                    }
                } else if (e.data.gridCellIndex !== null && e.data.gridCellIndex !== undefined) {
                    
                    var droppedType = e.data.element;
                    if (userTemplate) {
                        droppedType = userTemplate.elementType;
                    }
                    if (forbiddenInCells.indexOf(droppedType) !== -1) {
                        return;
                    }

                    if (userTemplate) {
                        addElementWithSettings(userTemplate.elementType, userTemplate.settings, e.data.parentId, e.data.gridCellIndex, templateChildrenCallback(userTemplate.children));
                    } else {
                        addElement(e.data.element, e.data.parentId, e.data.gridCellIndex);
                    }
                } else if (userTemplate) {
                    
                    addElementWithSettings(userTemplate.elementType, userTemplate.settings, e.data.parentId, e.data.position, templateChildrenCallback(userTemplate.children));
                } else if (e.data.element && e.data.element.startsWith('template:')) {
                    
                    var templateKey = e.data.element.replace('template:', '');
                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId + '/section-template',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ template: templateKey, parent_id: e.data.parentId, position: e.data.position }),
                        success: function() { refreshPreview(); }
                    });
                } else if (e.data.slideIndex !== undefined && e.data.slideIndex !== null) {
                    
                    addElementWithSettings(e.data.element,
                        { slide_index: parseInt(e.data.slideIndex) || 0 },
                        e.data.parentId, e.data.position);
                } else {
                    addElement(e.data.element, e.data.parentId, e.data.position);
                }
            }
            
            if (e.data.type === 'impulse-delete') {
                
                var deleteId = e.data.id || selectedElementId;
                if (deleteId) {
                    deleteElement(deleteId, !!e.data.id); 
                }
            }
            
            if (e.data.type === 'impulse-undo') {
                $('#impulse-undo').click();
            }
            
            if (e.data.type === 'impulse-redo') {
                $('#impulse-redo').click();
            }
            
            if (e.data.type === 'impulse-escape') {
                deselectElement();
            }

            

            
            
            function _readIframeScale(iframeEl) {
                if (!iframeEl) return 1;
                var wrap = iframeEl.parentElement;
                if (!wrap) return 1;
                var tx = '';
                try { tx = window.getComputedStyle(wrap).transform; } catch (e) { return 1; }
                if (!tx || tx === 'none') return 1;
                var m = tx.match(/matrix\(([^,]+),/);
                if (!m) return 1;
                var s = parseFloat(m[1]);
                return (isFinite(s) && s > 0) ? s : 1;
            }

            if (e.data.type === 'impulse-duplicate') {
                duplicateElement(e.data.id);
            }
            if (e.data.type === 'impulse-duplicate-slide') {
                duplicateSlide(parseInt(e.data.sliderId), parseInt(e.data.slideIndex));
            }

            if (e.data.type === 'impulse-context-menu') {
                _ctxData = e.data;
                var html = buildContextMenu(e.data);
                if (!html) return;

                

                

                var iframeEl = document.getElementById('impulse-iframe');
                var iframeRect = iframeEl ? iframeEl.getBoundingClientRect() : { left: 0, top: 0 };
                var _ctxZoom = _readIframeScale(iframeEl);
                var x = (e.data.x || 0) * _ctxZoom + iframeRect.left;
                var y = (e.data.y || 0) * _ctxZoom + iframeRect.top;
                ctxShow($contextMenu, x, y, html);
            }

            

            
            
            if (e.data.type === 'impulse-wrap-popover') {
                _ctxData = { element: { id: e.data.id, type: e.data.elementType } };
                var iframeEl = document.getElementById('impulse-iframe');
                var iframeRect = iframeEl ? iframeEl.getBoundingClientRect() : { left: 0, top: 0 };

                var _wrapZoom = _readIframeScale(iframeEl);
                var px = (e.data.x || 0) * _wrapZoom + iframeRect.left;
                var py = (e.data.y || 0) * _wrapZoom + iframeRect.top;
                var ph = ctxItem('wrap-section', 'Section')
                       + ctxItem('wrap-rows', 'Rows')
                       + ctxItem('wrap-columns', 'Columns')
                       + ctxItem('wrap-grid', 'Grid');
                $contextMenu.addClass('impulse-context-compact');
                ctxShow($contextMenu, px, py, ph);
            }

            
            if (e.data.type === 'impulse-context-menu') {
                $('#impulse-context-menu').removeClass('impulse-context-compact');
            }

            

            

            

            if (e.data.type === 'impulse-bg-position-changed') {
                var elId = e.data.id;
                var pos = e.data.position;
                var bgPosDevice = window.impulseDevice || 'desktop';
                var _bpKey = bgPosDevice === 'desktop' ? 'bg_position' : 'bg_position_' + bgPosDevice;
                
                if (selectedElementId == elId) {
                    $('input[name="bg_position"]').val(pos);
                    $('.impulse-bg-pos-btn').css({background: 'rgba(0,0,0,0.25)'}).removeClass('active').find('svg').attr('stroke', 'rgba(255,255,255,0.7)');
                    $('.impulse-bg-pos-btn[data-pos="' + pos + '"]').css({background: 'rgba(255,255,255,0.85)'}).addClass('active').find('svg').attr('stroke', ''+ImpC.surface2+'');

                    var _fm3 = String(pos).match(/(-?[\d.]+)%?\s+(-?[\d.]+)%?/);
                    var _ifr3 = document.getElementById('impulse-iframe');
                    if (_fm3 && _ifr3 && _ifr3.contentWindow) {
                        _ifr3.contentWindow.postMessage({ type: 'impulse-depth-focal',
                            x: Math.max(0, Math.min(1, parseFloat(_fm3[1]) / 100)),
                            y: Math.max(0, Math.min(1, parseFloat(_fm3[2]) / 100)) }, '*');
                    }

                    
                    var _exBp = $('.impulse-panel-right').data('existing-settings') || {};
                    _exBp[_bpKey] = pos;
                    $('.impulse-panel-right').data('existing-settings', _exBp);
                }
                
                var bgPosSaveData = {};
                bgPosSaveData[_bpKey] = pos;
                enqueueSave(elId, bgPosSaveData);
            }

            

            if (e.data.type === 'impulse-net-layout' && selectedElementId == e.data.id) {
                var netDev = e.data.device || 'desktop';
                if (netDev === 'desktop') {
                    var netMap = {};
                    (e.data.positions || []).forEach(function(p){ if (p && p.id != null) netMap[p.id] = { col: p.col, row: p.row }; });
                    var netCardsCur = [];
                    try { netCardsCur = JSON.parse($('input[name="cards"]').val() || '[]'); } catch (ex) { netCardsCur = []; }
                    netCardsCur.forEach(function(c){ if (netMap[c.id]) { c.col = netMap[c.id].col; c.row = netMap[c.id].row; } });
                    $('input[name="cards"]').val(JSON.stringify(netCardsCur));
                    $('.impulse-net-cards-list .impulse-net-card-item').each(function(){
                        var cid = ($(this).find('.net-card-id').val() || '').trim();
                        if (netMap[cid]) { $(this).attr('data-col', netMap[cid].col).attr('data-row', netMap[cid].row); }
                    });
                    enqueueSave(e.data.id, { cards: $('input[name="cards"]').val() });
                } else {

                    var posKey = 'positions_' + netDev;
                    var posJson = JSON.stringify(e.data.posMap || {});
                    var _es = $('.impulse-panel-right').data('existing-settings') || {};
                    _es[posKey] = posJson;
                    $('.impulse-panel-right').data('existing-settings', _es);
                    var _save = {}; _save[posKey] = posJson;
                    enqueueSave(e.data.id, _save);
                }
            }

            if (e.data.type === 'impulse-save-template') {
                saveAsTemplateById(e.data.id);
            }

            if (e.data.type === 'impulse-table-inline') {
                var ilId = e.data.id;
                var inlineItems = e.data.items || [];
                var inlineHeaders = e.data.headers || {};
                var existingSettings = {};
                if (selectedElementId == ilId) {
                    existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                }

                

                
                
                var _ilOldSnapshot = $.extend(true, {}, existingSettings);
                var existing = existingSettings.items || [];
                if (typeof existing === 'string') {
                    try { existing = JSON.parse(existing); } catch(ex) { existing = []; }
                }
                var merged = [];
                for (var ii = 0; ii < inlineItems.length; ii++) {
                    var base = existing[ii] || { icon: 'circle', url: '' };
                    var m = { icon: base.icon || 'circle', text: inlineItems[ii].text || '', url: base.url || '' };

                    

                    
                    
                    for (var _cc = 2; _cc <= 6; _cc++) {
                        var _ck = 'col' + _cc;
                        if (inlineItems[ii][_ck] !== undefined) m[_ck] = inlineItems[ii][_ck];
                        else if (base[_ck] !== undefined) m[_ck] = base[_ck];
                    }
                    merged.push(m);
                }
                var saveData = { items: merged };
                for (var hk in inlineHeaders) {
                    saveData[hk] = inlineHeaders[hk];
                }

                

                
                if (window.saveToHistory && selectedElementId == ilId
                    && Object.keys(_ilOldSnapshot).length > 0) {
                    var _ilNewSnapshot = $.extend(true, {}, _ilOldSnapshot, saveData);
                    if (JSON.stringify(_ilOldSnapshot) !== JSON.stringify(_ilNewSnapshot)) {
                        window.saveToHistory('update', {
                            elementId: ilId,
                            oldSettings: _ilOldSnapshot,
                            newSettings: _ilNewSnapshot
                        });
                    }
                }
                enqueueSave(ilId, saveData);
                if (selectedElementId == ilId) {
                    var updatedSettings = $.extend({}, existingSettings, saveData);
                    $('.impulse-panel-right').data('existing-settings', updatedSettings);
                    $('input[name="items"]').val(JSON.stringify(merged));
                    
                    $('.impulse-table-item-edit').each(function(idx) {
                        if (merged[idx]) {
                            $(this).find('.impulse-table-text').val(merged[idx].text);

                            
                            
                            var raw = String(merged[idx].text || '');
                            var plain = raw.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
                            var label = plain || 'Item ' + (idx + 1);
                            if (label.length > 24) label = label.substring(0, 22) + '...';
                            $(this).find('span').filter(function() { return $(this).css('text-overflow') === 'ellipsis'; }).text(label);
                        }
                    });
                }
            }
            
            if (e.data.type === 'impulse-reorder') {
                reorderElement(e.data.sourceId, e.data.targetId, e.data.position);
            }

            if (e.data.type === 'impulse-toast') {
                if (window.showToast) window.showToast(String(e.data.message || ''), e.data.kind || 'info');
                return;
            }

            if (e.data.type === 'impulse-move-into') {
                var src = e.data.sourceType || '';
                var tgt = e.data.targetType || '';
                
                if (e.data.sourceId === e.data.targetId) return;
                var layoutTypes = [ 'rows', 'columns'];
                    
                if (src === 'section' && tgt === 'section') return;
                if (src === 'slider' && tgt === 'slider') return;
                
                if (src === 'modal') return;
                
                if (layoutTypes.indexOf(tgt) !== -1 && forbiddenInCells.indexOf(src) !== -1) return;
                moveElementInto(e.data.sourceId, e.data.targetId, e.data.gridCellIndex, e.data.cellRow, e.data.cellCol, e.data.slideIndex);
            }

            if (e.data.type === 'impulse-drag-position') {
                lastDragPosition.x = e.data.x;
                lastDragPosition.y = e.data.y;
                lastDragPosition.fromIframe = true;
            }

            if (e.data.type === 'impulse-remap-done') {
                if (e.data.elementType === 'section') {

                    refreshPreview();
                }
                if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) {
                    setTimeout(updateStructureTree, 100);
                }
            }

            if (e.data.type === 'impulse-drag-active') {
                isDragActive = !!e.data.active;
                if (!isDragActive && pendingRefresh) {
                    pendingRefresh = false;
                    refreshPreview();
                }
            }

            if (e.data.type === 'impulse-media') {
                var elementId = e.data.id;
                var field = e.data.field;
                
                openImglibPicker({ label: 'Select Image' }, function(attachment) {
                    var settings = {};
                    settings[field] = attachment.id;
                    $.ajax({
                        url: Impulse.api + 'elements/' + elementId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: settings, page_id: Impulse.pageId }),
                        success: function() { refreshPreview(); }
                    });
                });

                mediaFrame.open();
            }

            if (e.data.type === 'impulse-content-changed') {
                var currentId = $('.impulse-panel-right').data('element-id');
                if (currentId == e.data.id) {

                    
                    
                    var _baseField = (e.data.field || '').replace(/_(tablet|mobile)$/, '');
                    
                    var $field = $('[name="' + _baseField + '"]');
                    if ($field.length) {
                        $field.val(e.data.value);
                    }
                    
                    var $editor = $('.impulse-richtext-editor[data-name="' + _baseField + '"]');
                    if ($editor.length && $editor.html() !== e.data.value) {
                        $editor.html(e.data.value);
                    }
                    
                    var existing = $('.impulse-panel-right').data('existing-settings') || {};
                    existing[e.data.field] = e.data.value;
                    $('.impulse-panel-right').data('existing-settings', existing);
                } else {
                    
                    window._pendingContentChange = { id: e.data.id, field: e.data.field, value: e.data.value };
                }
            }
        });
        
        var isRefreshing = false;
        var pendingRefresh = false;
        var pendingSelectElement = null; 
        var isDragActive = false; 
        var deletePending = {}; 
        
        function refreshPreview() {
            
            if (isDragActive) {
                pendingRefresh = true;
                return;
            }

            if (isRefreshing) {
                pendingRefresh = true;
                return;
            }
            
            isRefreshing = true;

            

            
            viewportPreserve.capture();
            var iframe = document.getElementById('impulse-iframe');
            var baseSrc = iframe.src.split('&t=')[0].split('&_=')[0].split('&device=')[0];

            if (!baseSrc || baseSrc === 'about:blank') {
                isRefreshing = false;
                return;
            }
            
            var _editSfxR = (window.Impulse && window.Impulse.previewEditSuffix) ? window.Impulse.previewEditSuffix : '';
            if (_editSfxR && baseSrc.indexOf('edit=1') === -1) baseSrc = baseSrc + _editSfxR;

            var scrollX = 0, scrollY = 0;
            try {
                if (iframe.contentWindow) {
                    scrollX = iframe.contentWindow.scrollX || 0;
                    scrollY = iframe.contentWindow.scrollY || 0;
                }
            } catch(e) {}

            try {
                if (iframe.contentWindow && iframe.contentWindow.impulseScreenMode &&
                    typeof iframe.contentWindow.impulseScreenMode.getCurrentScreen === 'function') {
                    window._savedScreenIndex = iframe.contentWindow.impulseScreenMode.getCurrentScreen();
                }
            } catch(e) {}

            
            var _rfSmNow = Impulse.pageSettings && (true);
            var _rfBgRaw = (Impulse.pageSettings && Impulse.pageSettings.bg_color) || '';
            var _rfBgNow = (_rfBgRaw && _rfBgRaw !== 'transparent') ? _rfBgRaw : (_rfSmNow ? '#000000' : ''+ImpC.surface+'');
            var _rfCanvas = document.querySelector('.impulse-canvas');
            if (_rfCanvas) _rfCanvas.style.background = _rfBgNow;

            
            iframe.style.height = '';

            

            

            

            iframe.style.pointerEvents = 'none';
            impulseShowLoadingBar();

            

            clearTimeout(window._iframeOpacitySafety);
            window._iframeOpacitySafety = setTimeout(function() {
                try { if (iframe.getAnimations) iframe.getAnimations().forEach(function(a){ try { a.cancel(); } catch(_e) {} }); } catch(_e) {}
                iframe.style.transition = 'none';
                iframe.style.opacity = '1';
                iframe.style.pointerEvents = '';
                void iframe.offsetWidth;
                iframe.style.transition = 'opacity 0.2s';
                
                isRefreshing = false;
                if (pendingRefresh) {
                    pendingRefresh = false;
                    refreshPreview();
                }
            }, 3000);
            
            var device = window.impulseDevice || 'desktop';
            var screenParam = '';
            if (window._savedScreenIndex > 0) screenParam = '&screen=' + window._savedScreenIndex;
            
            var _editSfx = (window.Impulse && window.Impulse.previewEditSuffix) ? window.Impulse.previewEditSuffix : '';
            
            if (_editSfx && baseSrc.indexOf('edit=1') === -1) baseSrc = baseSrc + _editSfx;
            iframe.src = baseSrc + '&device=' + device + screenParam + '&t=' + Date.now() + '&_=' + Math.random();
        }

        var _loadBarTimer = null, _loadBarProgress = 0;
        function impulseShowLoadingBar() {
            var bar = document.getElementById('impulse-load-bar');
            var fill = document.getElementById('impulse-load-bar-fill');
            if (!bar || !fill) return;
            clearInterval(_loadBarTimer);
            _loadBarProgress = 0;
            fill.style.transition = 'none';
            fill.style.width = '0%';
            bar.classList.add('active');
            void fill.offsetWidth;
            fill.style.transition = 'width 0.4s cubic-bezier(0.4,0,0.2,1)';
            _loadBarProgress = 15;
            fill.style.width = '15%';
            _loadBarTimer = setInterval(function() {
                if (_loadBarProgress >= 85) { clearInterval(_loadBarTimer); return; }
                _loadBarProgress += (85 - _loadBarProgress) * 0.08;
                fill.style.width = _loadBarProgress.toFixed(1) + '%';
            }, 200);
        }
        function impulseHideLoadingBar() {
            clearInterval(_loadBarTimer);
            var bar = document.getElementById('impulse-load-bar');
            var fill = document.getElementById('impulse-load-bar-fill');
            if (!bar || !fill) return;
            fill.style.width = '100%';
            setTimeout(function() { bar.classList.remove('active'); fill.style.width = '0%'; }, 350);
        }

        $('#impulse-iframe').on('load', function() {
            var iframe = document.getElementById('impulse-iframe');

            if (!iframe.src || iframe.src === 'about:blank') {
                return;
            }

            

            

            iframe.style.pointerEvents = '';

            impulseHideLoadingBar();

            isRefreshing = false;
            
            $(document).trigger('impulse:preview:loaded');

            delete iframe.dataset.savedScrollX;
            delete iframe.dataset.savedScrollY;
            var savedScrollX = 0, savedScrollY = 0; 

            if (pendingRefresh) {
                pendingRefresh = false;
                setTimeout(refreshPreview, 100);
                return;
            }

            if (typeof _iframeLoaded !== 'undefined') _iframeLoaded = true;

            setTimeout(function() {

                
                applyPageSettingsToPreview(Impulse.pageSettings || {});

                

                

                

                
                
                var _newScreenId = window._impulseNavigateToNewScreen || null;
                var _isScreenModeNow = (Impulse.pageSettings && (true));
                if (_isScreenModeNow && (_newScreenId || window._savedScreenIndex > 0)) {
                    var savedIdx = window._savedScreenIndex || 0;
                    window._savedScreenIndex = 0;
                    window._impulseNavigateToNewScreen = null;
                    try {
                        var iframe2 = document.getElementById('impulse-iframe');
                        if (iframe2 && iframe2.contentWindow && iframe2.contentWindow.impulseScreenMode) {
                            var count = iframe2.contentWindow.impulseScreenMode.getScreenCount();
                            var targetIdx = Math.min(savedIdx, count - 1);
                            if (_newScreenId) {
                                try {
                                    var doc2 = iframe2.contentDocument;
                                    var screens2 = doc2 ? doc2.querySelectorAll('.impulse-content-wrapper > .impulse-el[data-type="section"]') : [];
                                    for (var _si = 0; _si < screens2.length; _si++) {
                                        if (String(screens2[_si].getAttribute('data-id')) === String(_newScreenId)) {
                                            targetIdx = _si;
                                            break;
                                        }
                                    }
                                } catch(_e1) {}
                            }
                            
                            iframe2.contentWindow.impulseScreenMode.jumpToScreen(targetIdx);
                            
                            if (_newScreenId) {
                                window._pendingNewScreen = { idx: targetIdx, id: _newScreenId };
                            }
                        }
                    } catch(e) {}
                }

                

                

                
                var _iff = document.getElementById('impulse-iframe');
                if (_iff) {
                    try { if (_iff.getAnimations) _iff.getAnimations().forEach(function(a){ try { a.cancel(); } catch(_e) {} }); } catch(_e) {}
                    _iff.style.transition = 'none';
                    _iff.style.opacity = '1';
                    _iff.style.pointerEvents = '';
                    
                    void _iff.offsetWidth;
                    _iff.style.transition = 'opacity 0.15s';
                }

                [0, 50, 150, 300, 600, 1200].forEach(function(ms) {
                    setTimeout(function(){ if(typeof window.fitScreenCanvas==="function") window.fitScreenCanvas(); }, ms);
                });

                if (window._pendingNewScreen) {
                    var _pns = window._pendingNewScreen;
                    window._pendingNewScreen = null;
                    setTimeout(function() {
                        try {
                            selectedElementId = _pns.id;
                            selectedElementType = 'section';
                            postToIframe({ type: 'select-element', id: _pns.id });
                            openSettings(_pns.id, 'section');
                            setTimeout(updateScreenList, 300);
                        } catch(e) {}
                    }, 150);
                }

                var currentElementId = $('.impulse-panel-right').data('element-id');
                if (currentElementId && selectedElementType) {
                    setTimeout(function() {

                        

                        
                        var _skipLiveTypes = ['title', 'slider', 'carousel'];
                        if (_skipLiveTypes.indexOf(selectedElementType) === -1) {
                            livePreviewSettings();
                        }
                        
                        try {
                            var _ifrScroll = document.getElementById('impulse-iframe');
                            if (_ifrScroll && _ifrScroll.contentDocument) {
                                var _selEl = _ifrScroll.contentDocument.querySelector('.impulse-el[data-id="' + currentElementId + '"]');
                                if (_selEl) {
                                    _selEl.classList.add('selected');
                                }
                            }
                        } catch(e) {}
                        
                        try {
                            var iframe = document.getElementById('impulse-iframe');
                            if (iframe && iframe.contentWindow && iframe.contentWindow.impulseFitAllText) {
                                setTimeout(function() {
                                    iframe.contentWindow.impulseFitAllText();
                                }, 50);
                            }
                        } catch(e) {}
                        
                        if (selectedElementType === 'flip_box' && window.impulseFlipEditingSide === 'back') {
                            setTimeout(applyFlipBoxEditState, 100);
                        }
                    }, 50);
                }

                setTimeout(function() { viewportPreserve.restore(); }, 80);

                clearTimeout(window._iframeOpacitySafety);

                if ($('.impulse-structure-panel').is(':visible')) {
                    updateStructureTree();
                }

                updateScreenList();

                if (pendingSelectElement) {
                    var el = pendingSelectElement;
                    pendingSelectElement = null;

                    var layoutTypes = ['section',  'rows', 'columns', 'slider', 'grid', 'carousel'];
                    if (layoutTypes.indexOf(el.type) !== -1) {
                        
                        return;
                    }

                    setTimeout(function() {
                        
                        try {
                            var iframe = document.getElementById('impulse-iframe');
                            var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                            var newEl = iframeDoc.querySelector('.impulse-el[data-id="' + el.id + '"]');
                            if (newEl) {
                                iframeDoc.querySelectorAll('.impulse-el').forEach(function(x) { x.classList.remove('selected'); });
                                newEl.classList.add('selected');
                            }
                        } catch(e) {
                            console.error('Error selecting new element:', e);
                        }

                        openSettings(el.id, el.type);
                    }, 300);
                }
            }, 100);
        });

        
        
        var _lastNonLibraryTab = 'blocks';

        $(document).on('click', '.impulse-panel-tab', function() {
            var tab = $(this).data('tab');

            if (tab === 'templates' && $(this).hasClass('active')) {
                $('.impulse-panel-tab[data-tab="' + _lastNonLibraryTab + '"]').trigger('click');
                return;
            }
            
            if (tab !== 'templates') _lastNonLibraryTab = tab;

            if (tab === 'structure' && $(this).hasClass('active')) {
                var $panel = $('.impulse-structure-panel');
                var state = $panel.data('collapse-state') || 'open'; 
                if (state === 'open') {
                    
                    $('.impulse-structure-children').removeClass('expanded');
                    $('.impulse-structure-toggle').removeClass('expanded');
                    $panel.data('collapse-state', 'collapsed');
                } else {
                    
                    $('.impulse-structure-children').addClass('expanded');
                    $('.impulse-structure-toggle').addClass('expanded');
                    $panel.data('collapse-state', 'open');
                }
                return;
            }
            
            $('.impulse-panel-tab').removeClass('active');
            $(this).addClass('active');

            $('.impulse-blocks-panel').hide();
            $('.impulse-templates-panel').hide();
            $('.impulse-structure-panel').hide();
            
            if (tab === 'templates') {
                $('.impulse-templates-panel').show();
                $('.impulse-search').show();
                $('#impulse-bug-report-bar').hide();
            } else if (tab === 'structure') {
                $('.impulse-structure-panel').show().data('collapse-state', 'open');
                $('.impulse-search').hide();
                $('#impulse-bug-report-bar').hide();
                updateStructureTree();
            } else {
                $('.impulse-blocks-panel').show();
                $('.impulse-search').show();
                $('#impulse-bug-report-bar').show();
            }
        });

        

        window._impMultiSel = window._impMultiSel || [];
        window._impMultiParent = null;
        function impApplyMultiSelHighlight() {
            $('.impulse-structure-item').removeClass('multisel');
            (window._impMultiSel || []).forEach(function(id) {
                $('.impulse-structure-item[data-id="' + id + '"]').addClass('multisel');
            });
        }
        window.impApplyMultiSelHighlight = impApplyMultiSelHighlight;
        
        function impPushMultiSelToIframe() {
            try {
                var _msIfr = document.getElementById('impulse-iframe');
                if (_msIfr && _msIfr.contentWindow) {
                    _msIfr.contentWindow.postMessage({ type: 'impulse-multisel-apply', ids: (window._impMultiSel || []).slice() }, '*');
                }
            } catch (_e) {}
        }

        function updateStructureTree() {
            var $tree = $('#impulse-structure-tree');

            

            

            

            
            
            var _preservedExpand = { ids: {}, cells: {} };
            $tree.find('.impulse-structure-toggle.expanded').each(function() {
                var $item = $(this).closest('.impulse-structure-item');
                var dataId = $item.attr('data-id');
                if (dataId) {
                    _preservedExpand.ids[dataId] = true;
                } else {
                    var pId  = $item.attr('data-parent-id');
                    var cKey = $item.attr('data-cell');
                    if (pId !== undefined && cKey !== undefined) {
                        _preservedExpand.cells[pId + '|' + cKey] = true;
                    }
                }
            });

            $tree.empty();
            
            var _isSmTree = Impulse.pageSettings && (true);
            $('#impulse-structure-add-screen').toggle(!!_isSmTree);
            
            try {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) {
                    $tree.html('<div class="impulse-structure-empty">Loading...</div>');
                    setTimeout(updateStructureTree, 500);
                    return;
                }
                
                var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                var elements = iframeDoc.querySelectorAll('.impulse-el');

                if (elements.length === 0) {
                    $tree.html('<div class="impulse-structure-empty">No blocks yet.</div>');
                    return;
                }

                var rootElements = [];
                elements.forEach(function(el) {
                    var parent = el.parentElement;
                    
                    if (parent && (parent.tagName === 'BODY' || !parent.closest('.impulse-el'))) {
                        rootElements.push(el);
                    }
                });

                
                
                var isScreenMode = Impulse.pageSettings &&
                    (true);
                var screenCounter = 0;

                

                

                

                

                
                rootElements.forEach(function(el) {
                    var $built = buildStructureItem(el, iframeDoc);
                    if (isScreenMode && el.dataset.type === 'section' && !el.dataset.structLabel) {
                        screenCounter++;
                        $built.find('.struct-label-text').first().text(_impScNoun() + ' ' + screenCounter);
                    }
                    $tree.append($built);
                });

                
                
                if (Object.keys(_preservedExpand.ids).length || Object.keys(_preservedExpand.cells).length) {
                    $tree.find('.impulse-structure-item').each(function() {
                        var $it = $(this);
                        var match = false;
                        var dId = $it.attr('data-id');
                        if (dId && _preservedExpand.ids[dId]) {
                            match = true;
                        } else {
                            var pId  = $it.attr('data-parent-id');
                            var cKey = $it.attr('data-cell');
                            if (pId !== undefined && cKey !== undefined && _preservedExpand.cells[pId + '|' + cKey]) {
                                match = true;
                            }
                        }
                        if (match) {
                            $it.find('> .impulse-structure-toggle').addClass('expanded');
                            $it.next('.impulse-structure-children').addClass('expanded');
                        }
                    });
                }

                syncStructureSelection();
                updateScreenList();
            } catch(e) {
                console.error('Structure tree error:', e);
                $tree.html('<div class="impulse-structure-empty">Unable to load structure</div>');
            }
        }

        function buildStructureItem(el, doc) {
            var id = el.dataset.id;
            var type = el.dataset.type;
            var isSection = (type === 'section');

            var structLabel = isSection ? (el.dataset.structLabel || '') : '';
            var anchor      = isSection ? (el.dataset.anchor      || '') : '';

            var label = structLabel || getElementLabel(el, type);
            var isSelected = el.classList.contains('selected');

            var $item = $('<div class="impulse-structure-item' + (isSelected ? ' selected' : '') + '" data-id="' + id + '" data-type="' + type + '" draggable="true">');

            if (isSection) {
                var labelHtml = '<span class="impulse-structure-label struct-label-text" data-id="' + id + '" title="Double-click to rename">' + escapeHtml(label) + '</span>';
                if (anchor) {
                    labelHtml += '<span class="struct-anchor-badge" title="Anchor: #' + escapeHtml(anchor) + '">#' + escapeHtml(anchor) + '</span>';
                }
                $item.append(labelHtml);
            } else {
                $item.append('<span class="impulse-structure-label">' + escapeHtml(label) + '</span>');
            }

            
            
            var _typeLabel = type; 
            $item.append('<span class="impulse-structure-type">' + _typeLabel + '</span>');

            var sectionActions = isSection
                ? '<button type="button" class="struct-anchor-btn" data-id="' + id + '" title="Set anchor ID">'
                    + '<svg viewBox="0 0 24 24" width="11" height="11" stroke="'+ImpC.muted+'" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">'
                    + '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>'
                    + '</svg></button>'
                : '';

            $item.append('<div class="impulse-structure-actions">' + sectionActions +
                '<button type="button" class="structure-duplicate" title="Duplicate"><svg viewBox="0 0 24 24" width="11" height="11" stroke="'+ImpC.muted+'" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button>' +
                '<button type="button" class="structure-delete" title="Delete"><svg viewBox="0 0 24 24" width="11" height="11" stroke="'+ImpC.muted+'" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>' +
                '</div>');

            function wrapExpanded($parentItem, $childrenDiv) {
                $parentItem.prepend('<div class="impulse-structure-toggle expanded"><svg viewBox="0 0 24 24" stroke="currentColor" fill="none" stroke-width="2"><polyline points="9 6 15 12 9 18"/></svg></div>');
                $childrenDiv.addClass('expanded');
                var $w = $('<div>');
                $w.append($parentItem);
                $w.append($childrenDiv);
                return $w;
            }

            function wrapCollapsed($parentItem, $childrenDiv, childCount) {
                $parentItem.prepend('<div class="impulse-structure-toggle"><svg viewBox="0 0 24 24" stroke="currentColor" fill="none" stroke-width="2"><polyline points="9 6 15 12 9 18"/></svg></div>');
                if (childCount > 0) {
                    $parentItem.find('.impulse-structure-label').after('<span class="impulse-structure-count">' + childCount + '</span>');
                }
                var $w = $('<div>');
                $w.append($parentItem);
                $w.append($childrenDiv);
                return $w;
            }

            if (type === 'rows') {
                var rows = el.querySelectorAll('.impulse-rows-row');
                if (rows.length > 0) {
                    var $children = $('<div class="impulse-structure-children">');
                    var totalCellChildren = 0;
                    rows.forEach(function(row, rowIdx) {
                        var cells = row.querySelectorAll('.impulse-rows-cell');
                        cells.forEach(function(cell, colIdx) {
                            var cellKey = rowIdx + '-' + colIdx;
                            var isSelectedCell = cell.classList.contains('selected');
                            var cellChildren = cell.querySelectorAll(':scope > .impulse-cell-content > .impulse-el');
                            totalCellChildren += cellChildren.length;
                            
                            var $cellItem = $('<div class="impulse-structure-item impulse-structure-cell' + (isSelectedCell ? ' selected' : '') + '" data-parent-id="' + id + '" data-cell="' + cellKey + '">');
                            $cellItem.append('<span class="impulse-structure-label">R' + (rowIdx + 1) + ' C' + (colIdx + 1) + '</span>');
                            $cellItem.append('<span class="impulse-structure-type">cell</span>');
                            if (cellChildren.length > 0) {
                                var $cellChildrenDiv = $('<div class="impulse-structure-children">');
                                cellChildren.forEach(function(child) {
                                    $cellChildrenDiv.append(buildStructureItem(child, doc));
                                });
                                $children.append(wrapCollapsed($cellItem, $cellChildrenDiv, cellChildren.length));
                            } else {
                                $children.append($cellItem);
                            }
                        });
                    });
                    return wrapCollapsed($item, $children, totalCellChildren);
                }
            }

            if (type === 'columns') {
                var cols = el.querySelectorAll('.impulse-layout-col');
                if (cols.length > 0) {
                    var $children = $('<div class="impulse-structure-children">');
                    var totalCellChildren = 0;
                    cols.forEach(function(col, colIdx) {
                        var cells = col.querySelectorAll('.impulse-layout-cell');
                        cells.forEach(function(cell, rowIdx) {
                            var cellKey = colIdx + '-' + rowIdx;
                            var isSelectedCell = cell.classList.contains('selected');
                            var cellChildren = cell.querySelectorAll(':scope > .impulse-cell-content > .impulse-el');
                            totalCellChildren += cellChildren.length;
                            
                            var $cellItem = $('<div class="impulse-structure-item impulse-structure-cell' + (isSelectedCell ? ' selected' : '') + '" data-parent-id="' + id + '" data-cell="' + cellKey + '">');
                            $cellItem.append('<span class="impulse-structure-label">C' + (colIdx + 1) + ' R' + (rowIdx + 1) + '</span>');
                            $cellItem.append('<span class="impulse-structure-type">cell</span>');
                            if (cellChildren.length > 0) {
                                var $cellChildrenDiv = $('<div class="impulse-structure-children">');
                                cellChildren.forEach(function(child) {
                                    $cellChildrenDiv.append(buildStructureItem(child, doc));
                                });
                                $children.append(wrapCollapsed($cellItem, $cellChildrenDiv, cellChildren.length));
                            } else {
                                $children.append($cellItem);
                            }
                        });
                    });
                    return wrapCollapsed($item, $children, totalCellChildren);
                }
            }

            if (type === 'grid') {
                var gridContainer = el.querySelector('.impulse-grid');
                if (gridContainer) {
                    var gridCells = gridContainer.querySelectorAll(':scope > .impulse-grid-cell');
                    var hasChildren = false;
                    var totalCellChildren = 0;
                    var $children = $('<div class="impulse-structure-children">');
                    
                    gridCells.forEach(function(cell, cellIdx) {
                        var cellChildren = cell.querySelectorAll(':scope > .impulse-el');
                        var isSelectedCell = cell.classList.contains('selected');
                        totalCellChildren += cellChildren.length;
                        var $cellItem = $('<div class="impulse-structure-item impulse-structure-cell' + (isSelectedCell ? ' selected' : '') + '" data-parent-id="' + id + '" data-cell="' + cellIdx + '">');
                        $cellItem.append('<span class="impulse-structure-label">Cell ' + (cellIdx + 1) + '</span>');
                        $cellItem.append('<span class="impulse-structure-type">cell</span>');
                        if (cellChildren.length > 0) {
                            hasChildren = true;
                            var $cellChildrenDiv = $('<div class="impulse-structure-children">');
                            cellChildren.forEach(function(child) {
                                $cellChildrenDiv.append(buildStructureItem(child, doc));
                            });
                            $children.append(wrapCollapsed($cellItem, $cellChildrenDiv, cellChildren.length));
                        } else {
                            $children.append($cellItem);
                        }
                    });
                    
                    var directChildren = gridContainer.querySelectorAll(':scope > .impulse-el');
                    directChildren.forEach(function(child) {
                        hasChildren = true;
                        totalCellChildren++;
                        $children.append(buildStructureItem(child, doc));
                    });
                    
                    if (hasChildren) {
                        return wrapCollapsed($item, $children, totalCellChildren);
                    }
                }
            }

            if (type === 'slider' || type === 'carousel') {
                var slideDropzones = el.querySelectorAll('.impulse-dropzone[data-slide]');
                if (slideDropzones.length > 0) {
                    var slideMap = {};
                    slideDropzones.forEach(function(dropzone) {
                        var idx = parseInt(dropzone.dataset.slide) || 0;
                        if (!slideMap[idx]) slideMap[idx] = [];
                        dropzone.querySelectorAll(':scope > .impulse-el').forEach(function(c) { slideMap[idx].push(c); });
                    });
                    var slideIndices = Object.keys(slideMap).map(Number).sort(function(a,b){return a-b;});
                    var $children = $('<div class="impulse-structure-children">');
                    var _carousel = el.querySelector('.impulse-new-slider');
                    var _curSlide = _carousel ? (parseInt(_carousel.dataset.currentSlide) || 0) : 0;
                    slideIndices.forEach(function(idx) {
                        var kids = slideMap[idx];
                        var isCur = idx === _curSlide;
                        var $slideItem = $('<div class="impulse-structure-item impulse-structure-slide' + (isCur ? ' selected' : '') + '" data-slider-id="' + id + '" data-slide-index="' + idx + '">');
                        $slideItem.append('<span class="impulse-structure-label">Slide ' + (idx + 1) + '</span>');
                        $slideItem.append('<span class="impulse-structure-type">slide</span>');
                        if (kids.length > 0) {
                            var $slideKids = $('<div class="impulse-structure-children">');
                            kids.forEach(function(child) { $slideKids.append(buildStructureItem(child, doc)); });
                            $children.append(wrapExpanded($slideItem, $slideKids));
                        } else {
                            $children.append($slideItem);
                        }
                    });
                    return wrapExpanded($item, $children);
                }
            }

            if (type === 'modal') {
                var popupContent = el.querySelector('.impulse-modal-content');
                if (popupContent) {
                    var popupChildren = popupContent.querySelectorAll(':scope > .impulse-el');
                    if (popupChildren.length > 0) {
                        var $children = $('<div class="impulse-structure-children">');
                        popupChildren.forEach(function(child) {
                            $children.append(buildStructureItem(child, doc));
                        });
                        return wrapExpanded($item, $children);
                    }
                }
            }

            if (type === 'modal') {
                var ocContent = el.querySelector('.impulse-modal-drawer-content');
                if (ocContent) {
                    var ocChildren = ocContent.querySelectorAll(':scope > .impulse-el');
                    if (ocChildren.length > 0) {
                        var $children = $('<div class="impulse-structure-children">');
                        ocChildren.forEach(function(child) {
                            $children.append(buildStructureItem(child, doc));
                        });
                        return wrapExpanded($item, $children);
                    }
                }
            }

            var children = el.querySelectorAll(':scope > .impulse-section > .impulse-container > .impulse-dropzone > .impulse-el, :scope > .impulse-section > .impulse-container > .impulse-el, :scope > .impulse-container-el > .impulse-el');
            if (children.length > 0) {
                var $children = $('<div class="impulse-structure-children">');
                children.forEach(function(child) {
                    $children.append(buildStructureItem(child, doc));
                });
                return wrapExpanded($item, $children);
            }
            
            return $item;
        }

        function getElementLabel(el, type) {
            switch(type) {
                case 'text':
                    var p = el.querySelector('.impulse-text p');
                    return p ? p.innerText.substring(0, 30) : 'Text';
                case 'button':
                    var btn = el.querySelector('.impulse-button a');
                    return btn ? btn.innerText : 'Button';
                case 'image':
                    var img = el.querySelector('img');
                    return img && img.alt ? img.alt.substring(0, 30) : 'Image';
                case 'slider':
                    return 'Slider';
                case 'grid':
                    var gridContainer = el.querySelector('.impulse-grid');
                    if (gridContainer) {
                        
                        var style = gridContainer.getAttribute('style') || '';
                        var colMatch = style.match(/grid-template-columns:\s*repeat\((\d+)/);
                        var cols = colMatch ? parseInt(colMatch[1]) : 3;
                        var rowMatch = style.match(/grid-template-rows:\s*repeat\((\d+)/);
                        var rows = rowMatch ? parseInt(rowMatch[1]) : 1;
                        
                        var children = gridContainer.querySelectorAll(':scope > .impulse-el, :scope > .impulse-grid-cell').length;
                        rows = Math.ceil(children / cols) || 1;
                        return 'Grid ' + cols + 'x' + rows;
                    }
                    return 'Grid';
                case 'rows':
                    var rows = el.querySelectorAll('.impulse-rows-row');
                    if (rows.length > 0) {
                        var colCounts = [];
                        rows.forEach(function(row) {
                            colCounts.push(row.querySelectorAll('.impulse-rows-cell').length);
                        });
                        var isUniform = colCounts.every(function(c) { return c === colCounts[0]; });

                        
                        if (isUniform) {
                            return 'Rows ' + colCounts[0] + 'x' + colCounts.length;
                        } else {
                            return 'Rows (' + colCounts.join('-') + ')';
                        }
                    }
                    return 'Rows';
                case 'columns':
                    var lgCols = el.querySelectorAll('.impulse-layout-col');
                    if (lgCols.length > 0) {
                        var cellCounts = [];
                        lgCols.forEach(function(col) {
                            cellCounts.push(col.querySelectorAll('.impulse-layout-cell').length);
                        });
                        return 'Columns ' + lgCols.length + 'col (' + cellCounts.join('-') + ')';
                    }
                    return 'Columns';
                default:
                    var nameMap = {
                        'icon_card': 'Icon Card', 'table': 'Table', 'flip_box': 'Flip Box',
                        'social': 'Social', 'carousel': 'Carousel', 'map': 'Map',
                        'contact': 'Contact', 'login': 'Login', 'register': 'Register',
                        'checkout': 'Checkout',
                        'cart': 'Cart',
                        'plans': 'Plans',
                        'products': 'Products',
                        'booking': 'Booking',
                        'account': 'Account', 'receipt': 'Receipt', 'shipping': 'Shipping',
                        'header': 'Header', 'footer': 'Footer',
                        'code': 'Code', 'copyright': 'Copyright',
                        'slider': 'Slider', 'title': 'Title', 'price_list': 'Price List',
                        'modal': 'Modal',
                        'instagent': 'Instagent'
                    };
                    if (type === 'shape') {
                        return el.querySelector('img') ? 'Graphic' : 'SVG Shape';
                    }
                    return nameMap[type] || type.charAt(0).toUpperCase() + type.slice(1).replace(/_/g, ' ');
            }
        }

        $(document).on('click', '.impulse-structure-toggle', function(e) {
            e.stopPropagation();
            var $toggle = $(this);
            var $item = $toggle.closest('.impulse-structure-item');
            var $children = $item.next('.impulse-structure-children');
            if ($children.length) {
                $toggle.toggleClass('expanded');
                $children.toggleClass('expanded');
            }
        });

        $(document).on('click', '.impulse-structure-item', function(e) {
            if ($(e.target).closest('.impulse-structure-actions').length) return;
            if ($(e.target).closest('.impulse-structure-toggle').length) return;
            if ($(e.target).closest('.struct-color-dot').length) return;
            if ($(e.target).closest('.struct-anchor-badge').length) return;
            if ($(e.target).is('.struct-rename-input,.struct-anchor-input')) return;

            

            

            

            

            

            
            
            if (e.shiftKey || e.metaKey || e.ctrlKey) {
                var _msId = $(this).data('id');
                if (_msId !== undefined && _msId !== null && _msId !== '') {
                    e.preventDefault(); e.stopPropagation();
                    var _msParentRow = $(this).closest('.impulse-structure-children').prev('.impulse-structure-item');
                    var _msParent = _msParentRow.length ? String(_msParentRow.data('id')) : '__root__';

                    

                    

                    

                    
                    
                    var $sibs = (function($me) {
                        var p = $me[0].parentElement;
                        
                        if (p && !p.classList.contains('impulse-structure-children')
                              && !p.classList.contains('impulse-screen-list')) {
                            p = p.parentElement;
                        }
                        if (!p) return $();
                        var sibs = [];
                        Array.from(p.children).forEach(function(c) {
                            if (c.classList.contains('impulse-structure-item') && c.dataset.id) {
                                sibs.push(c);
                            } else if (c.firstElementChild
                                     && c.firstElementChild.classList.contains('impulse-structure-item')
                                     && c.firstElementChild.dataset.id) {
                                sibs.push(c.firstElementChild);
                            }
                        });
                        return $(sibs);
                    })($(this));
                    var _ids = $sibs.map(function(){ return String($(this).data('id')); }).get();
                    var _ci = _ids.indexOf(String(_msId));
                    var _ai = (window._impMultiAnchor != null && String(window._impMultiAnchor) !== '')
                              ? _ids.indexOf(String(window._impMultiAnchor)) : -1;
                    if (_ai !== -1 && _ci !== -1) {
                        
                        var _lo = Math.min(_ai, _ci), _hi = Math.max(_ai, _ci);
                        window._impMultiSel = [];
                        for (var _ri = _lo; _ri <= _hi; _ri++) {
                            window._impMultiSel.push($sibs.eq(_ri).data('id'));
                        }
                    } else {

                        
                        
                        window._impMultiSel = [_msId];
                        window._impMultiAnchor = _msId;
                    }
                    window._impMultiParent = _msParent;
                    impApplyMultiSelHighlight();
                    impPushMultiSelToIframe();
                    return;
                }
            }

            if (window._impMultiSel && window._impMultiSel.length) {
                window._impMultiSel = []; window._impMultiParent = null;
                impApplyMultiSelHighlight(); impPushMultiSelToIframe();
            }

            
            var _impAnchorId = $(this).data('id');
            if (_impAnchorId !== undefined && _impAnchorId !== null && _impAnchorId !== '') window._impMultiAnchor = _impAnchorId;
            e.stopPropagation();

            

            
            
            var $autoExpand = $(this).next('.impulse-structure-children');
            if ($autoExpand.length && !$autoExpand.hasClass('expanded')) {
                $autoExpand.addClass('expanded');
                $(this).find('> .impulse-structure-toggle').addClass('expanded');
            }

            var $item = $(this);
            var id = $item.data('id');
            var type = $item.data('type');
            var cellKey = $item.data('cell');
            var parentId = $item.data('parent-id');

            if (cellKey !== undefined && cellKey !== null && parentId) {
                
                var childId = $item.data('child-id');
                if (childId) {
                    try {
                        var iframe = document.getElementById('impulse-iframe');
                        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        iframeDoc.querySelectorAll('.impulse-el').forEach(function(el) { el.classList.remove('selected'); });
                        var childEl = iframeDoc.querySelector('.impulse-el[data-id="' + childId + '"]');
                        if (childEl) {
                            childEl.classList.add('selected');
                            scrollToElementInIframe(childId);
                            $('.impulse-structure-item').removeClass('selected');
                            $item.addClass('selected');
                            openSettings(childId, childEl.dataset.type);
                        }
                    } catch(ex) { console.error(ex); }
                    return;
                }

                var isGridCell = String(cellKey).indexOf('-') === -1;
                
                try {
                    var iframe = document.getElementById('impulse-iframe');
                    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

                    iframeDoc.querySelectorAll('.impulse-el').forEach(function(el) { el.classList.remove('selected'); });
                    iframeDoc.querySelectorAll('.impulse-rows-cell').forEach(function(c) { c.classList.remove('selected'); });
                    iframeDoc.querySelectorAll('.impulse-grid-cell').forEach(function(c) { c.classList.remove('selected'); });
                    iframeDoc.querySelectorAll('.impulse-layout-cell').forEach(function(c) { c.classList.remove('selected'); });

                    var parentEl = iframeDoc.querySelector('.impulse-el[data-id="' + parentId + '"]');
                    if (parentEl) {
                        parentEl.classList.add('selected');
                        
                        if (isGridCell) {
                            
                            var cell = parentEl.querySelector('.impulse-grid-cell[data-cell="' + cellKey + '"]');
                            if (cell) cell.classList.add('selected');
                        } else {
                            
                            var parts = String(cellKey).split('-');
                            var row = parseInt(parts[0]);
                            var col = parseInt(parts[1]);
                            var parentType = parentEl.dataset.type;
                            
                            if (parentType === 'columns') {
                                var layoutCell = parentEl.querySelector('.impulse-layout-cell[data-col="' + row + '"][data-row="' + col + '"]');
                                if (layoutCell) layoutCell.classList.add('selected');
                            } else {
                                var cgCell = parentEl.querySelector('.impulse-rows-cell[data-row="' + row + '"][data-col="' + col + '"]');
                                if (cgCell) cgCell.classList.add('selected');
                            }
                        }
                    }
                } catch(ex) { console.error(ex); }

                scrollToElementInIframe(parentId);

                $('.impulse-structure-item').removeClass('selected');
                $item.addClass('selected');
                
                if (isGridCell) {
                    
                    selectedGridCellIndex = parseInt(cellKey, 10);
                    selectedGridParentId = parentId;
                    selectedCellGridParentId = null;
                    selectedCellGridCellKey = null;
                    openSettings(parentId, 'grid');

                    

                    setTimeout(function() {
                        var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                        var panelSettings = collectSettingsFromPanel();
                        var mergedSettings = Object.assign({}, existingSettings, panelSettings);
                        $('.impulse-panel-right').data('existing-settings', mergedSettings);
                        var html = buildSettingsForm('grid', mergedSettings, []);
                        $('#impulse-settings-body').html(html);
                    }, 100);
                } else {
                    
                    selectedCellGridParentId = parentId;
                    selectedCellGridCellKey = cellKey;
                    selectedGridParentId = null;
                    selectedGridCellIndex = null;
                    
                    var parentType = 'rows';
                    try {
                        var pEl = document.getElementById('impulse-iframe').contentDocument.querySelector('.impulse-el[data-id="' + parentId + '"]');
                        if (pEl) parentType = pEl.dataset.type || 'rows';
                    } catch(ex) {}
                    
                    openSettings(parentId, parentType);
                    
                    setTimeout(function() {
                        $('input[name="_selected_cells"]').val(JSON.stringify([cellKey]));
                        var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};

                        
                        rebuildCellGridEditorPanel(parentId, existingSettings, [cellKey]);
                    }, 100);
                }
                
                return;
            }

            if (!id || !type) return;

            if (type === 'section') {
                var $toggle = $item.find('> .impulse-structure-toggle, .impulse-structure-toggle').first();
                var $children = $item.next('.impulse-structure-children');
                if ($children.length) {
                    $toggle.toggleClass('expanded');
                    $children.toggleClass('expanded');
                }
            }

            

            

            

            
            selectedGridParentId = null;
            selectedGridCellIndex = null;
            selectedCellGridParentId = null;
            selectedCellGridCellKey = null;

            var elFoundInIframe = false;
            try {
                var iframe = document.getElementById('impulse-iframe');
                var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                iframeDoc.querySelectorAll('.impulse-el').forEach(function(el) { el.classList.remove('selected'); });
                iframeDoc.querySelectorAll('.impulse-rows-cell').forEach(function(c) { c.classList.remove('selected'); });
                iframeDoc.querySelectorAll('.impulse-grid-cell').forEach(function(c) { c.classList.remove('selected'); });
                iframeDoc.querySelectorAll('.impulse-layout-cell').forEach(function(c) { c.classList.remove('selected'); });
                var el = iframeDoc.querySelector('.impulse-el[data-id="' + id + '"]');
                if (el) {
                    el.classList.add('selected');
                    elFoundInIframe = true;
                }
            } catch(ex) {}

            if (!elFoundInIframe && type !== 'section') {
                updateStructureTree();
                return;
            }

            scrollToElementInIframe(id);

            if ((Impulse.pageSettings && (true)) && type === 'section') {
                window._impulseSetSceneDim(false);
            }

            
            $('.impulse-structure-item').removeClass('selected');
            $item.addClass('selected');

            openSettings(id, type);
        });

        $(document).on('contextmenu', '.impulse-structure-item', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $item = $(this);
            var id = $item.data('id');
            var type = $item.data('type');

            
            
            if ((!id || !type) && $item.hasClass('impulse-structure-cell')) {
                var pId = parseInt($item.data('parent-id'));
                var cIdx = parseInt($item.data('cell'));
                if (!pId || isNaN(cIdx)) return;
                $('.impulse-structure-item').removeClass('selected');
                $item.addClass('selected');
                
                var $parentItem = $item.closest('.impulse-structure-children').prev('.impulse-structure-item');
                var parentType = $parentItem.length ? $parentItem.data('type') : 'grid';
                selectedElementId = pId;
                selectedElementType = parentType;
                window.selectedGridCellIndex = cIdx;
                _ctxData = { gridCell: { gridId: pId, cellIdx: cIdx, gridType: parentType } };
                var cellHtml = buildCellContextMenu(_ctxData);
                if (cellHtml) ctxShow($('#impulse-context-menu'), e.clientX, e.clientY, cellHtml);
                openSettings(pId, parentType);
                return;
            }
            if (!id || !type) return;

            $('.impulse-structure-item').removeClass('selected');
            $item.addClass('selected');

            try {
                var iframe = document.getElementById('impulse-iframe');
                var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                iframeDoc.querySelectorAll('.impulse-el').forEach(function(el) { el.classList.remove('selected'); });
                var el = iframeDoc.querySelector('.impulse-el[data-id="' + id + '"]');
                if (el) el.classList.add('selected');
            } catch(ex) {}

            selectedElementId = id;
            selectedElementType = type;

            var ctx = { element: { id: id, type: type } };
            
            var $parentChildren = $item.parent('.impulse-structure-children');
            if ($parentChildren.length) {
                var $parentItem = $parentChildren.prev('.impulse-structure-item');
                if ($parentItem.length) {
                    ctx.parent = { id: $parentItem.data('id'), type: $parentItem.data('type') };
                    
                    var $gpChildren = $parentItem.parent('.impulse-structure-children');
                    var $gpItem = $gpChildren.length ? $gpChildren.prev('.impulse-structure-item') : $();
                    if ($gpItem.length) ctx.grandparent = { id: $gpItem.data('id'), type: $gpItem.data('type') };
                }
            }
            
            _ctxData = ctx;
            var html = buildContextMenu(ctx);
            if (!html) return;
            ctxShow($('#impulse-context-menu'), e.clientX, e.clientY, html);
            
            openSettings(id, type);
        });

        
        $(document).on('click', '.impulse-structure-slide', function(e) {
            e.stopPropagation();
            var sliderId = $(this).data('slider-id');
            var slideIdx = parseInt($(this).data('slide-index')) || 0;
            if (!sliderId) return;
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-go-to-slide', sliderId: String(sliderId), slideIndex: slideIdx }, '*');
            }
            
            openSettings(sliderId, 'slider');
        });

        $(document).on('click', '.structure-duplicate', function(e) {
            e.stopPropagation();
            var $item = $(this).closest('.impulse-structure-item');
            var id = $item.data('id');
            if (!id) return;
            try {
                var _ifrDoc = document.getElementById('impulse-iframe').contentDocument;
                if (_ifrDoc && !_ifrDoc.querySelector('.impulse-el[data-id="' + id + '"]')) {
                    updateStructureTree();
                    return;
                }
            } catch(ex) {}
            duplicateElement(id);
        });

        

        
        $(document).on('input change', 'input[name="width_pct"]', function() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            var pct = parseInt($(this).val()) || 90;
            try {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return;
                var el = iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                if (!el) return;

                
                var targets = el.querySelectorAll(':scope > div, :scope > section, :scope > .impulse-grid, :scope > .impulse-rows, :scope > .impulse-layout-grid');
                targets.forEach(function(t) {
                    t.style.setProperty('max-width', pct + '%', 'important');
                    t.style.setProperty('margin-left', 'auto', 'important');
                    t.style.setProperty('margin-right', 'auto', 'important');
                });
            } catch(e) {}
        });

        

        
        
        var _structDelArmedId = null, _structDelTimer = null;
        function _disarmStructDelete() {
            _structDelArmedId = null;
            if (_structDelTimer) { clearTimeout(_structDelTimer); _structDelTimer = null; }
            $('.impulse-structure-item.struct-del-armed').removeClass('struct-del-armed');
        }
        $(document).on('click', '.structure-delete', function(e) {
            e.stopPropagation();
            var $item = $(this).closest('.impulse-structure-item');
            var id = $item.data('id');
            if (!id) return;
            if (deletePending[id]) return; 
            if (_structDelArmedId === id) {
                
                _disarmStructDelete();
                deleteElement(id, true);
                return;
            }
            
            _disarmStructDelete();
            _structDelArmedId = id;
            $item.addClass('struct-del-armed');
            _structDelTimer = setTimeout(_disarmStructDelete, 3000);
        });
        
        $(document).on('click', function(e) {
            if (_structDelArmedId === null) return;
            if ($(e.target).closest('.structure-delete').length) return;
            _disarmStructDelete();
        });

        
        function saveStructField(id, fields) {
            $.ajax({
                url: Impulse.api + 'elements/' + id,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ settings: fields, page_id: Impulse.pageId })}).done(function() {
                setTimeout(function() {
                    try {
                        var iframeDoc = document.getElementById('impulse-iframe').contentDocument;
                        var el = iframeDoc.querySelector('.impulse-el[data-id="' + id + '"]');
                        if (el) {
                            if ('struct_label' in fields) el.dataset.structLabel = fields.struct_label;
                            if ('struct_color' in fields) el.dataset.structColor = fields.struct_color;
                            if ('css_id'        in fields) el.dataset.anchor      = fields.css_id;
                        }
                    } catch(ex) {}
                    
                    updateScreenList();
                }, 150);
            });
        }

        function getElementLabelFromIframe(id) {
            try {
                var el = document.getElementById('impulse-iframe').contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                return el ? getElementLabel(el, el.dataset.type || 'section') : 'Section';
            } catch(ex) { return 'Section'; }
        }

        function startRename($item) {
            if ($item.find('.struct-rename-input').length) return;
            var id      = $item.data('id');
            var $lbl    = $item.find('.struct-label-text');
            var current = $lbl.text();
            var $input  = $('<input class="struct-rename-input" type="text" maxlength="40">').val(current);
            $lbl.replaceWith($input);
            $input.focus().select();

            function commit() {
                var val     = $input.val().trim();
                var display = val || getElementLabelFromIframe(id) || 'Section';
                $input.replaceWith('<span class="impulse-structure-label struct-label-text" data-id="' + id + '" title="Double-click to rename">' + escapeHtml(display) + '</span>');
                saveStructField(id, { struct_label: val });
            }
            $input.on('blur', commit);
            $input.on('keydown', function(e) {
                if (e.key === 'Enter')  { e.preventDefault(); $input.trigger('blur'); }
                if (e.key === 'Escape') { $input.val(current); $input.trigger('blur'); }
            });
        }

        $(document).on('dblclick', '.struct-label-text', function(e) {
            e.stopPropagation();
            startRename($(this).closest('.impulse-structure-item'));
        });

        function startAnchorEdit($item) {
            if ($item.find('.struct-anchor-input').length) {
                $item.find('.struct-anchor-input').trigger('blur'); return;
            }
            var id = $item.data('id');
            var current = '';
            try {
                var iframeEl = document.getElementById('impulse-iframe').contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                if (iframeEl) current = iframeEl.dataset.anchor || '';
            } catch(ex) {}

            var $input = $('<input class="struct-anchor-input" type="text" maxlength="60" placeholder="e.g. pricing">').val(current);
            var $badge = $item.find('.struct-anchor-badge');
            if ($badge.length) $badge.after($input); else $item.find('.struct-label-text').after($input);
            $input.focus().select();

            function commit() {
                var raw = $input.val().trim();
                var val = raw.replace(/[^a-z0-9_-]/gi, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').toLowerCase();
                $input.remove();
                $item.find('.struct-anchor-badge').remove();
                if (val) {
                    $item.find('.struct-label-text').after('<span class="struct-anchor-badge" title="Anchor: #' + escapeHtml(val) + '">#' + escapeHtml(val) + '</span>');
                }
                saveStructField(id, { css_id: val });
            }
            $input.on('blur', commit);
            $input.on('keydown', function(e) {
                if (e.key === 'Enter')  { e.preventDefault(); $input.trigger('blur'); }
                if (e.key === 'Escape') { $input.remove(); }
            });
        }

        $(document).on('click', '.struct-anchor-btn', function(e) {
            e.stopPropagation();
            startAnchorEdit($(this).closest('.impulse-structure-item'));
        });
        $(document).on('click', '.struct-anchor-badge', function(e) {
            e.stopPropagation();
            startAnchorEdit($(this).closest('.impulse-structure-item'));
        });

        var _structColorPalette = [
            { key: 'white',  hex: ''+ImpC.text+'' },
            { key: 'silver', hex: ''+ImpC.muted+''    },
            { key: 'grey',   hex: '#666'    },
            { key: 'slate',  hex: '#444'    },
            { key: 'dark',   hex: ''+ImpC.panel+'' }];

        $(document).on('click', '.struct-color-dot', function(e) {
            e.stopPropagation();
            var id    = $(this).data('id');
            var $dot  = $(this);
            var $item = $dot.closest('.impulse-structure-item');

            $('.struct-color-popover').remove();
            if ($dot.data('picker-open')) { $dot.removeData('picker-open'); return; }
            $dot.data('picker-open', true);

            var current = '';
            _structColorPalette.forEach(function(c) {
                if ($item.hasClass('sc-' + c.key)) current = c.key;
            });

            var $pop = $('<div class="struct-color-popover">');
            $pop.append('<div class="struct-color-swatch clear-swatch" data-key="" title="Remove color">&#10005;</div>');
            _structColorPalette.forEach(function(c) {
                var sel = current === c.key ? ' selected' : '';
                $pop.append('<div class="struct-color-swatch' + sel + '" data-key="' + c.key + '" data-hex="' + c.hex + '" style="background:' + c.hex + '" title="' + c.key + '"></div>');
            });

            var off = $dot.offset();
            $pop.css({ top: off.top + $dot.outerHeight() + 4, left: off.left });
            $('body').append($pop);

            $pop.on('click', '.struct-color-swatch', function(ev) {
                ev.stopPropagation();
                var key = $(this).data('key') || '';
                var hex = $(this).data('hex') || '';
                _structColorPalette.forEach(function(c) { $item.removeClass('sc-' + c.key); });
                if (key) {
                    $item.addClass('sc-' + key);
                    $item.css('border-left', '3px solid ' + hex);
                    $dot.addClass('has-color').css('background', hex);
                } else {
                    $item.css('border-left', '');
                    $dot.removeClass('has-color').css('background', '');
                }
                saveStructField(id, { struct_color: key });
                $pop.remove();
                $dot.removeData('picker-open');
            });

            setTimeout(function() {
                $(document).one('click.struct-color-outside', function() {
                    $pop.remove();
                    $dot.removeData('picker-open');
                });
            }, 10);
        });

        (function() {
            var _lpTimer = null;
            var _lpFired = false;

            document.addEventListener('click', function(e) {
                if (_lpFired && $(e.target).closest('.struct-color-dot').length) {
                    _lpFired = false;
                    e.stopImmediatePropagation();
                    e.preventDefault();
                }
            }, true);

            $(document).on('mousedown', '.struct-color-dot', function(e) {
                if (e.button !== 0) return;
                var $dot  = $(this);
                var id    = $dot.data('id');
                var $item = $dot.closest('.impulse-structure-item');
                _lpFired = false;

                _lpTimer = setTimeout(function() {
                    _lpFired = true;
                    $('.struct-color-popover').remove();
                    $dot.removeData('picker-open');
                    openStructMiniPicker($dot, $item, id);
                }, 500);
            });

            $(document).on('mouseup mouseleave', '.struct-color-dot', function() {
                clearTimeout(_lpTimer);
            });

            function openStructMiniPicker($dot, $item, id) {
                
                var currentHex = '#888888';
                var inlineStyle = $dot[0].style.background || $dot[0].style.backgroundColor || '';
                var bg = inlineStyle || $dot.css('background-color');
                var m = bg.match(/(\d+),\s*(\d+),\s*(\d+)/);
                if (m) currentHex = '#' + [m[1],m[2],m[3]].map(function(n){ return (+n).toString(16).padStart(2,'0'); }).join('');
                else if (/^#[0-9a-f]{6}$/i.test(bg)) currentHex = bg;

                var r = parseInt(currentHex.substr(1,2),16)||128,
                    g = parseInt(currentHex.substr(3,2),16)||128,
                    b = parseInt(currentHex.substr(5,2),16)||128;
                var hsv = rgbToHsv(r,g,b);
                var hue = Math.round(hsv.h), sat = Math.round(hsv.s), val = Math.round(hsv.v);

                var html  = '<div class="struct-mini-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'">';
                    html += '<div class="smp-gradient" style="background-color:hsl('+hue+',100%,50%)">';
                    html += '<div class="smp-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div>';
                    html += '</div>';
                    html += '<div class="smp-hue"><div class="smp-thumb" style="left:'+((hue/360)*100)+'%"></div></div>';
                    html += '</div>';

                var $picker = $(html);
                var off     = $dot.offset();
                var left    = Math.max(4, off.left - 75);
                if (left + 164 > $(window).width() - 4) left = $(window).width() - 168;
                $picker.css({ position:'fixed', top:(off.top + $dot.outerHeight() + 6)+'px', left:left+'px' });
                $('body').append($picker);

                function smpHex() {
                    var h = parseFloat($picker.data('hue'))||0,
                        s = parseFloat($picker.data('sat'))||0,
                        v = parseFloat($picker.data('val'))||100;
                    var rgb = hsvToRgb(h,s,v);
                    return '#'+[rgb.r,rgb.g,rgb.b].map(function(n){return n.toString(16).padStart(2,'0');}).join('');
                }

                function smpUpdate() {
                    var h = parseFloat($picker.data('hue'))||0,
                        s = parseFloat($picker.data('sat'))||0,
                        v = parseFloat($picker.data('val'))||100;
                    $picker.find('.smp-gradient').css('background-color','hsl('+h+',100%,50%)');
                    $picker.find('.smp-cursor').css({left:s+'%',top:(100-v)+'%'});
                    $picker.find('.smp-thumb').css('left',((h/360)*100)+'%');
                    var hex = smpHex();
                    $dot.css('background', hex).addClass('has-color');
                    $item.css('border-left', '3px solid ' + hex);
                }

                function smpCommit() {
                    var hex = smpHex();
                    _structColorPalette.forEach(function(c){ $item.removeClass('sc-'+c.key); });
                    saveStructField(id, { struct_color: hex });
                    $picker.remove();
                    $(document).off('mousedown.smp-outside');
                }

                $picker.on('mousedown', '.smp-gradient', function(e) {
                    e.preventDefault(); e.stopPropagation();
                    function move(ev) {
                        var rect = $picker.find('.smp-gradient')[0].getBoundingClientRect();
                        $picker.data('sat', Math.round(Math.max(0,Math.min(100,((ev.clientX-rect.left)/rect.width)*100))));
                        $picker.data('val', Math.round(Math.max(0,Math.min(100,100-((ev.clientY-rect.top)/rect.height)*100))));
                        smpUpdate();
                    }
                    $(document).on('mousemove.smp-grad', move);
                    $(document).one('mouseup.smp-grad', function(){ $(document).off('mousemove.smp-grad'); });
                    move(e);
                });

                $picker.on('mousedown', '.smp-hue', function(e) {
                    e.preventDefault(); e.stopPropagation();
                    function move(ev) {
                        var rect = $picker.find('.smp-hue')[0].getBoundingClientRect();
                        $picker.data('hue', Math.round(Math.max(0,Math.min(360,((ev.clientX-rect.left)/rect.width)*360))));
                        smpUpdate();
                    }
                    $(document).on('mousemove.smp-hue', move);
                    $(document).one('mouseup.smp-hue', function(){ $(document).off('mousemove.smp-hue'); });
                    move(e);
                });

                setTimeout(function() {
                    $(document).on('mousedown.smp-outside', function(ev) {
                        if (!$(ev.target).closest('.struct-mini-picker').length) {
                            smpCommit();
                        }
                    });
                }, 20);
            }
        })();

        

        
        
        window.syncStructureSelection = function() { return syncStructureSelection.apply(this, arguments); };
        function syncStructureSelection() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id && typeof selectedElementId !== 'undefined') id = selectedElementId;
            $('.impulse-structure-item').removeClass('selected');
            if (!id) return;

            
            
            var sId = String(id);
            var $match = $('.impulse-structure-item').filter(function() {
                var d = $(this);
                return String(d.data('id')) === sId || String(d.data('child-id')) === sId;
            });

            

            

            

            

            
            
            var $cellMatch = $();
            try {
                var _ifrSS = document.getElementById('impulse-iframe');
                var _docSS = _ifrSS && (_ifrSS.contentDocument || _ifrSS.contentWindow.document);
                if (_docSS) {
                    var _selCellDom = _docSS.querySelector(
                        '.impulse-grid-cell.selected, .impulse-rows-cell.selected, .impulse-layout-cell.selected'
                    );
                    if (_selCellDom) {
                        var _domParent = _selCellDom.getAttribute('data-parent');
                        var _domCell   = _selCellDom.getAttribute('data-cell');
                        if (_domParent && _domCell !== null) {
                            $cellMatch = $('.impulse-structure-cell').filter(function() {
                                var d = $(this);
                                return String(d.data('parent-id')) === String(_domParent)
                                    && String(d.data('cell'))      === String(_domCell);
                            });
                        }
                    }
                }
            } catch (_ssDomErr) {}
            if (!$cellMatch.length && typeof selectedGridParentId !== 'undefined' && selectedGridParentId &&
                typeof selectedGridCellIndex !== 'undefined' && selectedGridCellIndex !== null) {
                $cellMatch = $('.impulse-structure-cell').filter(function() {
                    var d = $(this);
                    return String(d.data('parent-id')) === String(selectedGridParentId)
                        && String(d.data('cell')) === String(selectedGridCellIndex);
                });
            } else if (!$cellMatch.length && typeof selectedCellGridParentId !== 'undefined' && selectedCellGridParentId &&
                typeof selectedCellGridCellKey !== 'undefined' && selectedCellGridCellKey !== null) {
                $cellMatch = $('.impulse-structure-cell').filter(function() {
                    var d = $(this);
                    return String(d.data('parent-id')) === String(selectedCellGridParentId)
                        && String(d.data('cell')) === String(selectedCellGridCellKey);
                });
            }
            if ($cellMatch.length) $match = $cellMatch;
            if (!$match.length) return;
            $match.addClass('selected');

            

            

            
            
            var _ancId = $match.first().data('id');
            if (_ancId !== undefined && _ancId !== null && _ancId !== '') {
                window._impMultiAnchor = _ancId;
            }

            $match.each(function() {
                $(this).parents('.impulse-structure-children').each(function() {
                    var $children = $(this);
                    if (!$children.hasClass('expanded')) $children.addClass('expanded');
                    var $parentItem = $children.prev('.impulse-structure-item');
                    if (!$parentItem.length) {
                        
                        $parentItem = $children.parent().prev().find('> .impulse-structure-item').first();
                    }
                    $parentItem.find('> .impulse-structure-toggle').addClass('expanded');
                });
            });

            

            

            

            
            
            var _firstEl = $match.first()[0];
            if (_firstEl && typeof _firstEl.scrollIntoView === 'function') {
                requestAnimationFrame(function() {
                    try { _firstEl.scrollIntoView({ block: 'nearest', behavior: 'auto' }); } catch (_e) {}
                });
            }
        }

        
        
        (function() {
            var draggedId = null;
            var draggedType = null;
            var $panel = $('.impulse-structure-panel');
            
            $(document).on('dragstart', '.impulse-structure-item[data-id]', function(e) {
                draggedId = $(this).data('id');
                draggedType = $(this).data('type');
                $(this).addClass('dragging');
                $panel.addClass('dragging');
                e.originalEvent.dataTransfer.effectAllowed = 'move';
                e.originalEvent.dataTransfer.setData('text/plain', String(draggedId));
                
                e.stopPropagation();
            });
            
            $(document).on('dragover', '.impulse-structure-item[data-id]', function(e) {

                

                
                if (window._impulseSrowDragging) return;
                e.preventDefault();
                e.stopPropagation();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                if (!draggedId) return;
                var targetId = $(this).data('id');
                if (targetId == draggedId) return;

                $('.impulse-structure-item').removeClass('drop-above drop-below drop-inside');
                
                var rect = this.getBoundingClientRect();
                var y = e.originalEvent.clientY - rect.top;
                var h = rect.height;
                var targetType = $(this).data('type');
                var isContainer = ['section','container','row','column','stack','inline','slider','modal'].indexOf(targetType) !== -1;

                var targetIsRoot = !$(this).parent().closest('.impulse-structure-children').length;
                if ((Impulse.pageSettings && (true)) && targetIsRoot) {
                    
                    if (isContainer && draggedType !== 'section') {
                        $(this).addClass('drop-inside');
                    }
                    return;
                }

                if ((Impulse.pageSettings && (true)) && (draggedType === 'section')) {
                    return;
                }
                
                if (isContainer) {
                    
                    if (y < h * 0.25) {
                        $(this).addClass('drop-above');
                    } else if (y > h * 0.75) {
                        $(this).addClass('drop-below');
                    } else {
                        $(this).addClass('drop-inside');
                    }
                } else {
                    
                    if (y < h * 0.5) {
                        $(this).addClass('drop-above');
                    } else {
                        $(this).addClass('drop-below');
                    }
                }
            });

            $(document).on('dragover', '.impulse-structure-root-drop', function(e) {
                
                if ((Impulse.pageSettings && (true))) {
                    e.preventDefault();
                    return;
                }
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                $(this).addClass('drag-over');
                $('.impulse-structure-item').removeClass('drop-above drop-below drop-inside');
            });
            
            $(document).on('dragleave', '.impulse-structure-root-drop', function() {
                $(this).removeClass('drag-over');
            });
            
            $(document).on('drop', '.impulse-structure-root-drop', function(e) {
                e.preventDefault();
                $(this).removeClass('drag-over');
                if (!draggedId) return;
                
                if ((Impulse.pageSettings && (true))) { cleanup(); return; }

                moveElementInto(draggedId, 0, null, null, null, null, true);
                cleanup();
            });
            
            $(document).on('dragleave', '.impulse-structure-item', function() {
                $(this).removeClass('drop-above drop-below drop-inside');
            });

            
            
            $(document).on('dragover', '.impulse-structure-cell[data-parent-id]', function(e) {

                if (!draggedElement && !draggedId) return;
                e.preventDefault();
                e.stopPropagation();
                $('.impulse-structure-item').removeClass('drop-above drop-below drop-inside drop-target-cell');
                $(this).addClass('drop-target-cell');
            });
            
            $(document).on('dragleave', '.impulse-structure-cell[data-parent-id]', function() {
                $(this).removeClass('drop-target-cell');
            });
            
            $(document).on('drop', '.impulse-structure-cell[data-parent-id]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('drop-target-cell');
                var parentId = parseInt($(this).attr('data-parent-id')) || 0;
                var cellKey = String($(this).attr('data-cell') || '');
                if (!parentId) return;
                
                var $parentItem = $('.impulse-structure-item[data-id="' + parentId + '"]');
                var parentType = $parentItem.data('type') || 'grid';

                

                if (draggedId) {
                    if (String(draggedId) === String(parentId)) { cleanup(); return; }
                    var moveBody = { parent_id: parentId, page_id: Impulse.pageId || 0 };
                    if (parentType === 'grid') {
                        var gIdx = parseInt(cellKey);
                        if (!isNaN(gIdx)) moveBody.grid_cell_index = gIdx;
                    } else {
                        var rcParts = cellKey.split('-');
                        var rRow = parseInt(rcParts[0]);
                        var rCol = parseInt(rcParts[1]);
                        if (!isNaN(rRow) && !isNaN(rCol)) {
                            moveBody.cell_row = rRow;
                            moveBody.cell_col = rCol;
                        }
                    }
                    var movedSourceId = draggedId;
                    cleanup();

                    

                    
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + movedSourceId,
                        method: 'GET',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function(elementData) {
                            var oldParentId  = elementData.parent_id || 0;
                            var oldSortOrder = elementData.sort_order || 0;
                            var oldCellRow   = (elementData.settings && elementData.settings._cell_row !== undefined) ? elementData.settings._cell_row : null;
                            var oldCellCol   = (elementData.settings && elementData.settings._cell_col !== undefined) ? elementData.settings._cell_col : null;
                            $.ajax({
                                url: Impulse.api + 'elements/' + movedSourceId + '/move-into',
                                method: 'POST',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify(moveBody),
                                success: function() {
                                    saveToHistory('move', {
                                        sourceId: movedSourceId,
                                        targetId: parentId,
                                        oldParentId: oldParentId,
                                        oldSortOrder: oldSortOrder,
                                        oldCellRow: oldCellRow,
                                        oldCellCol: oldCellCol,
                                        gridCellIndex: (moveBody.grid_cell_index !== undefined ? moveBody.grid_cell_index : null),
                                        cellRow: (moveBody.cell_row !== undefined ? moveBody.cell_row : null),
                                        cellCol: (moveBody.cell_col !== undefined ? moveBody.cell_col : null)
                                    });
                                    refreshPreview();
                                    setTimeout(updateStructureTree, 400);
                                },
                                error: function(xhr) {
                                    window.showToast && window.showToast('Move failed', 'error');
                                    console.error('move-into failed:', xhr.responseText);
                                }
                            });
                        },
                        error: function() {
                            
                            $.ajax({
                                url: Impulse.api + 'elements/' + movedSourceId + '/move-into',
                                method: 'POST',
                                headers: { 'X-WP-Nonce': Impulse.nonce },
                                contentType: 'application/json',
                                data: JSON.stringify(moveBody),
                                success: function() { refreshPreview(); setTimeout(updateStructureTree, 400); },
                                error: function(xhr) { console.error('move-into failed:', xhr.responseText); }
                            });
                        }
                    });
                    return;
                }

                var element = draggedElement;
                if (!element) return;
                if (parentType === 'grid') {
                    var cellIndex = parseInt(cellKey);
                    if (!isNaN(cellIndex)) addElement(element, parentId, cellIndex);
                } else {
                    
                    var parts = cellKey.split('-');
                    var row = parseInt(parts[0]);
                    var col = parseInt(parts[1]);
                    if (!isNaN(row) && !isNaN(col)) addElementToCellGridCell(element, parentId, row, col);
                }
            });
            
            $(document).on('drop', '.impulse-structure-item[data-id]', function(e) {

                
                
                if (window._impulseSrowDragging) return;
                e.preventDefault();
                e.stopPropagation();
                if (!draggedId) return;
                var targetId = $(this).data('id');
                if (targetId == draggedId) { cleanup(); return; }

                if ((Impulse.pageSettings && (true))) {
                    if ($(this).hasClass('drop-above') || $(this).hasClass('drop-below')) {
                        var targetIsRoot = !$(this).parent().closest('.impulse-structure-children').length;
                        if (targetIsRoot) { cleanup(); return; }
                    }
                    
                    if ($(this).hasClass('drop-inside') && (draggedType === 'section')) {
                        cleanup(); return;
                    }
                }

                

                

                var _multi = (window._impMultiSel && window._impMultiSel.length >= 2
                              && window._impMultiSel.indexOf(draggedId) !== -1)
                           ? window._impMultiSel.slice() : null;

                

                if ($(this).hasClass('drop-above')) {
                    reorderElement(draggedId, targetId, 'before', true);
                } else if ($(this).hasClass('drop-below')) {
                    reorderElement(draggedId, targetId, 'after', true);
                } else if ($(this).hasClass('drop-inside')) {
                    if (_multi) {
                        _structMultiMoveInto(_multi, targetId, function() {
                            refreshPreview();
                            setTimeout(updateStructureTree, 250);
                            window.showToast && window.showToast('Moved ' + _multi.length + ' blocks');
                        });
                        window._impMultiSel = []; window._impMultiParent = null;
                    } else {
                        moveElementInto(draggedId, targetId, null, null, null, null, true);
                    }
                }
                cleanup();
            });

            

            function _structMultiMoveInto(ids, containerId, done) {
                var i = 0;
                (function next() {
                    if (i >= ids.length) { if (done) done(); return; }
                    var sid = ids[i++];
                    if (String(sid) === String(containerId)) { next(); return; }
                    $.ajax({
                        url: Impulse.api + 'elements/' + sid + '/move-into',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ parent_id: containerId, page_id: Impulse.pageId || 0 })
                    }).always(function() { next(); });
                })();
            }
            
            $(document).on('dragend', '.impulse-structure-item', function() {
                cleanup();
            });
            
            function cleanup() {
                draggedId = null;
                draggedType = null;
                $('.impulse-structure-item').removeClass('dragging drop-above drop-below drop-inside');
                $panel.removeClass('dragging');
                $('.impulse-structure-root-drop').removeClass('drag-over');
            }
        })();

        function openSettings(id, type) {
            
            if (!id || !type) {
                console.error('openSettings: invalid id or type', id, type);
                return;
            }

            if (window._sceneScreensHidden) {
                window._sceneScreensHidden = false;
                var _iframe = document.getElementById('impulse-iframe');
                if (_iframe && _iframe.contentWindow) {
                    _iframe.contentWindow.postMessage({ type: 'impulse-scene-screens-dim', hidden: false }, '*');
                }
            }

            clearTimeout(autoSaveTimer);
            clearTimeout(autoRefreshTimer);

            var currentId = $('.impulse-panel-right').data('element-id');
            if (currentId && currentId != id && 
                !isPageSettingsMode() &&
                $('#impulse-settings-body').text().indexOf('Loading') === -1) {

                if (typeof cellGridSaveTimer !== 'undefined' && cellGridSaveTimer) {
                    clearTimeout(cellGridSaveTimer);
                    cellGridSaveTimer = null;
                }
                
                var currentSettings = collectSettingsFromPanel();
                
                $.ajax({
                    url: Impulse.api + 'elements/' + currentId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: currentSettings, page_id: Impulse.pageId }),
                    async: false
                });
            }
            
            selectedElementId = id;
            selectedElementType = type;
            
            window.selectedElementId = id;
            window.selectedElementType = type;
            $(document).trigger('impulse:selection:changed', [id, type]);

            

            $('.impulse-panel-right').data('element-id', id);
            $('.impulse-panel-right').data('element-type', type).attr('data-element-type', type);

            syncStructureSelection();

            
            if (window.postToIframe) postToIframe({ type: 'select-element', id: id });

            $('#impulse-settings-body').html('<div style="padding:20px;text-align:center;color:'+ImpC.muted+'">Loading...</div>');
            $('#impulse-chat-toggle-footer').hide();
            $('#impulse-mobile-optimize-footer').hide();
            var displayName = type === 'icon_card' ? 'Icon Card' : type === 'table' ? 'Table' : type === 'slider' ? 'Slider' : type === 'contact' ? 'Contact' : type === 'columns' ? 'Columns' : type === 'rows' ? 'Rows' : type === 'carousel' ? 'Carousel' : type === 'map' ? 'Map' : type === 'social' ? 'Social' : type === 'unfold' ? 'Unfold' : type === 'shape' ? 'Shape' : type === 'code' ? 'Code' : type === 'products' ? 'Products' : type === 'cart' ? 'Cart' : type === 'login' ? 'Login' : type === 'plans' ? 'Plans' : type === 'title' ? 'Title' : type === 'title' ? 'Title' : type === 'modal' ? 'Modal' : type === 'price_list' ? 'Price List' : type === 'shipping' ? 'Shipping' : type === 'instagent' ? 'Instagent' : type.charAt(0).toUpperCase() + type.slice(1).replace(/_/g, ' ');

            
            if (type === 'section' && Impulse.pageSettings &&
                (true)) {
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentDocument) {
                    var el = iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (el && (!el.parentElement.closest || !el.parentElement.closest('.impulse-el'))) {
                        displayName = _impScNoun();
                    }
                }
            }
            $('#impulse-settings-title').text(displayName + ' Settings');

            

            
            $.ajax({
                url: Impulse.api + 'elements/' + id,
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                data: { _: Date.now(), page_id: Impulse.pageId }
            }).done(function(data) {
                
                if ($('.impulse-panel-right').data('element-id') != id) {
                    return;
                }

                var elementType = data.section_type || type;

                selectedElementType = elementType;
                $('.impulse-panel-right').data('element-type', elementType);
                
                var settings = data.settings || {};

                
                if (settings.bg_color === '#000000') settings.bg_color = 'transparent';
                
                if (elementType === 'grid' && settings.bg_color && settings.bg_color !== 'transparent') {
                    settings.bg_color = 'transparent';
                }
                if (elementType === 'flip_box' && settings.bg_color) {
                    settings.bg_color = '';
                }

                var children = data.children || [];

                if (elementType === 'rows') {
                    var cached = getCachedCellGridSettings(id);
                    if (cached) {
                        
                        settings = $.extend({}, settings, cached);
                        
                        if (Array.isArray(settings.rows)) {
                            settings.rows = JSON.stringify(settings.rows);
                        }
                    }
                    
                    $('.impulse-panel-right').data('cell-grid-children', children);
                }

                $('.impulse-panel-right').data('existing-settings', settings);

                if (elementType === 'product_carousel') {
                    window._prevPcSettings = jQuery.extend(true, {}, settings);
                } else {
                    window._prevPcSettings = null;
                }
                if (elementType === 'products') {
                    window.productGridPrevSettings = jQuery.extend(true, {}, settings);
                }

                $('.impulse-panel-right').data('parent-id', data.parent_id || null);
                
                var device = window.impulseDevice || 'desktop';
                var panelSettings = device !== 'desktop' ? resolveDeviceSettings(settings, device) : settings;
                if (device !== 'desktop' && (elementType === 'title' || elementType === 'title')) {
                    panelSettings = autoMobileDefaults(panelSettings, elementType, device);
                }
                var html = buildSettingsForm(elementType, panelSettings, children);
                _laInitializing = true;
                window._impulseRendering = true;
                $('#impulse-settings-body').html(html);
                window._impulseRendering = false;

                
                if ($('#impulse-screen-bar').is(':visible')) {
                    $('#impulse-screen-bar').hide();
                    if (typeof window.fitScreenCanvas === 'function') window.fitScreenCanvas();
                }
                setTimeout(function() { _laInitializing = false; }, 200);

                
                $(document).trigger('impulse:settings-panel-loaded', [id, elementType]);

                if (elementType !== 'products' && elementType !== 'products') {
                    postToIframe({ type: 'impulse-quickview-preview-close' });
                }
                var displayNameFinal = elementType === 'icon_card' ? 'Icon Card' : elementType === 'table' ? 'Table' : elementType === 'slider' ? 'Slider' : elementType === 'contact' ? 'Contact' : elementType === 'columns' ? 'Columns' : elementType === 'rows' ? 'Rows' : elementType === 'carousel' ? 'Carousel' : elementType === 'map' ? 'Map' : elementType === 'social' ? 'Social' : elementType === 'unfold' ? 'Unfold' : elementType === 'shape' ? (settings.graphic_type === 'image' ? 'Graphic' : 'Shape') : elementType === 'code' ? 'Code' : elementType === 'products' ? 'Products' : elementType === 'cart' ? 'Cart' : elementType === 'login' ? 'Login' : elementType === 'plans' ? 'Plans' : elementType === 'title' ? 'Title' : elementType === 'title' ? 'Title' : elementType === 'modal' ? 'Modal' : elementType === 'price_list' ? 'Price List' : elementType === 'shipping' ? 'Shipping' : elementType === 'instagent' ? 'Instagent' : elementType.charAt(0).toUpperCase() + elementType.slice(1).replace(/_/g, ' ');
                var _scrModeOn = Impulse.pageSettings &&
                    (true);
                if (elementType === 'section' && _scrModeOn && !data.parent_id) {
                    displayNameFinal = _impScNoun();
                }
                $('#impulse-settings-title').text(displayNameFinal + ' Settings');
                
                if (elementType === 'section' && _scrModeOn && !data.parent_id) {
                    var _cgEnabled = !(window.Impulse && window.Impulse.chat && window.Impulse.chat.settings && window.Impulse.chat.settings.enabled === '0');
                    if (_cgEnabled) $('#impulse-chat-toggle-footer').show();
                }
                
                if (elementType === 'section' && (Impulse.pageSettings && (true)) && !data.parent_id) {
                    $('.impulse-section-scroll-reveal-wrap').hide();
                }

                
                
                $('#impulse-settings-body textarea').each(function() {
                    if ($(this).hasClass('impulse-richtext-html')) return;
                    this.style.height = 'auto';
                    this.style.height = (this.scrollHeight + 2) + 'px';
                });

                
                window.videoPrev = null;
                window.iconTextPrev = null;
                window.iconPrev = null;
                window.textPrev = null;
                window.galleryPrev = null;
                window.googleMapPrevSettings = null;
                window.sectionPrev = null;
                window.displayTextPrev = null;
                window._pendingRefreshId = null;
                window._dt3dPrevSnap = null;
                window.priceListPrev = null;
                
                if (window._impulseAlignCache && id) {
                    delete window._impulseAlignCache[id];
                }

                

                var layoutTypes = ['section',  'rows', 'columns', 'slider', 'grid'];
                if (layoutTypes.indexOf(elementType) === -1 && elementType !== 'title') {
                    livePreviewSettings();
                } else if (elementType === 'title') {

                    
                    window.displayTextPrev = JSON.parse(JSON.stringify(collectSettingsFromPanel()));
                } else {

                    var initSettings = collectSettingsFromPanel();
                    if (elementType === 'section') window.sectionPrev = JSON.parse(JSON.stringify(initSettings));
                    if (elementType === 'slider' || elementType === 'carousel') {
                        window.newSliderPrevSettings = JSON.parse(JSON.stringify(initSettings));
                    }
                    if (elementType === 'grid' || elementType === 'rows' || elementType === 'columns' || elementType === 'slider') {

                        if (!window._impulsePrevStructural) window._impulsePrevStructural = {};
                        var _elCfg = window.ImpulseElementConfig ? window.ImpulseElementConfig.get(elementType) : null;
                        var _structKeys = _elCfg ? (_elCfg.structural || []) : [];
                        var _seedObj = {};
                        for (var _si = 0; _si < _structKeys.length; _si++) {
                            _seedObj[_structKeys[_si]] = initSettings[_structKeys[_si]];
                        }
                        window._impulsePrevStructural[id] = JSON.stringify(_seedObj);
                    }
                }

                if (elementType === 'table') {
                    initIconListSortable();
                }

                
                if (elementType === 'chart') {
                    initChartEntriesSortable();
                }

                if (elementType === 'price_list') {
                    initPriceListSortable();
                }

                
                if (elementType === 'booking') {
                    window.bookingBlockPrev = JSON.parse(JSON.stringify(settings));
                }

                if (elementType === 'booking') {
                    var $bkSel = $('#impulse-settings-body select[name="service_id"]');
                    var doPopulate = function(services) {
                        var curVal = $bkSel.val();
                        $bkSel.find('option:not(:first)').remove();
                        (services || []).forEach(function(sv) {
                            var opt = $('<option>').val(sv.id).text(sv.name);
                            if (sv.id == curVal) opt.prop('selected', true);
                            $bkSel.append(opt);
                        });
                    };
                    if (bookingsState.services && bookingsState.services.length) {
                        doPopulate(bookingsState.services);
                    } else {
                        $.post(window.Impulse.products.ajaxurl, {
                            action: 'instinctor_get_services',
                            nonce: window.Impulse.adminNonce
                        }, function(res) {
                            if (res.success) {
                                bookingsState.services = res.data.services || [];
                                doPopulate(bookingsState.services);
                            }
                        });
                    }
                }

                
                if (elementType === 'video') {
                    loadVideoMasks();
                }

                if (elementType === 'rows') {
                    initGridSelectorFromRows();
                    updateGridSelectorVisual();
                    
                    updateCellGridCache(id, settings);
                    
                    initCellGridDragDrop();
                }
            }).fail(function(xhr, status, error) {
                console.error('openSettings failed — HTTP ' + xhr.status + ' ' + error + ' (id=' + id + ' type=' + type + ')', xhr.responseText ? xhr.responseText.substring(0, 300) : '');
                $('#impulse-settings-body').html('<div style="padding:20px;text-align:center;color:'+ImpC.muted+'">Failed to load settings (HTTP ' + xhr.status + ')</div>');
            });
        }

        function renderSettingsPanel(type, settings) {
            if (!type) return;
            var device = window.impulseDevice || 'desktop';
            var panelSettings = device !== 'desktop' ? resolveDeviceSettings(settings, device) : settings;
            if (device !== 'desktop' && (type === 'title' || type === 'title')) {
                panelSettings = autoMobileDefaults(panelSettings, type, device);
            }
            var html = buildSettingsForm(type, panelSettings, []);
            _laInitializing = true;
            $('#impulse-settings-body').html(html);
            upgradeCheckboxes(document.getElementById('impulse-settings-body'));

            

            

            

            

            setTimeout(function() { _laInitializing = false; }, 200);
            $('.impulse-panel-right').data('existing-settings', settings);
        }
        
        var containerTypes = ['section',  'rows', 'columns', 'slider', 'modal'];
        function buildSettingsForm(type, settings, children) {
            
            $('.impulse-panel-right').attr('data-panel-device', window.impulseDevice || 'desktop');
            var html = '';
            children = children || [];

            html += '<div class="impulse-setting-group">';
            
            switch(type) {
                case 'section':
                    
                    var _bgImgDev = (typeof getResponsiveValue === 'function')
                        ? (getResponsiveValue(settings, 'bg_image', '') || '')
                        : (settings.bg_image || '');
                    var hasBgImage = _bgImgDev;

                    

                    var _bgCovers = !!(hasBgImage || (settings.bg_depth_image && settings.bg_depth_map));

                    var isScreenMode = Impulse.pageSettings && (true);

                    

                    var isRootScreen = isScreenMode && !$('.impulse-panel-right').data('parent-id');

                    

                    var sectionTab = 'layout'; 
                    html += '<div class="impulse-section-tabs" style="display:flex;border-bottom:1px solid '+ImpC.border+';margin:0 -12px 12px -12px;padding:0">';
                    html += '<button type="button" class="impulse-section-tab active" data-stab="layout" style="flex:1;height:32px;border:none;background:transparent;color:'+ImpC.white+';font-size:11px;cursor:pointer;border-bottom:2px solid '+ImpC.white+';text-transform:uppercase;letter-spacing:0.5px">Layout</button>';
                    html += '<button type="button" class="impulse-section-tab" data-stab="effects" style="flex:1;height:32px;border:none;background:transparent;color:#666;font-size:11px;cursor:pointer;border-bottom:2px solid transparent;text-transform:uppercase;letter-spacing:0.5px">Animation</button>';
                    html += '</div>';

                    html += '<div class="impulse-section-tab-content" data-stab="layout">';

                    

                    

                    var _isNativeScroll = !!(Impulse.pageSettings && Impulse.pageSettings.body_scroll === 'classic');

                    
                    if (isRootScreen && _isNativeScroll) {
                        html += '<div class="impulse-section-divider" style="margin-top:0">Height</div>';
                        html += '<div class="impulse-margin-grid" style="margin-bottom:10px">';
                        html += settingSliderR('screen_min_height_vh', 'Min height', settings, 0, 0, 100, 'vh');
                        html += '</div>';
                    }
                    if (isRootScreen && !_isNativeScroll) {
                        var _scrnRv = settings.screen_transition || '';
                        var _scrnRvBtns = [
                            ['', 'Inherit'],
                            ['z_depth', 'Depth']
                            
                        ];

                        var _revOpen = (function(){ try { return localStorage.getItem('impulse_fold_reveal') !== '0'; } catch(e){ return true; } })();
                        html += '<div class="impulse-section-divider impulse-fold-head" data-fold="reveal" style="margin-top:0;cursor:pointer;display:flex;align-items:center;justify-content:space-between;user-select:none">Reveal Effect <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="opacity:0.55;transition:transform 0.12s ease-in-out;transform:rotate(' + (_revOpen ? '0' : '-90') + 'deg)"><path d="m6 9 6 6 6-6"/></svg></div>';
                        html += '<div class="impulse-fold-body" data-fold-body="reveal" style="display:' + (_revOpen ? 'block' : 'none') + '">';
                        html += '<div class="impulse-reveal-group" data-key="screen_transition" style="margin-bottom:8px">';
                        html += '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin-bottom:6px">';
                        _scrnRvBtns.forEach(function(b) {
                            html += '<button type="button" class="impulse-reveal-btn' + (_scrnRv === b[0] ? ' active' : '') + '" data-value="' + b[0] + '">' + b[1] + '</button>';
                        });
                        html += '</div>';
                        html += '<input type="hidden" name="screen_transition" value="' + _scrnRv + '">';
                        html += '</div>';

                        
                        var _scrnSkip = settings.screen_skip === '1' || settings.screen_skip === 1 || settings.screen_skip === true;
                        html += '<label style="display:flex;align-items:center;gap:6px;height:26px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;white-space:nowrap;margin-bottom:10px"><input type="checkbox" name="screen_skip" value="1"' + (_scrnSkip ? ' checked' : '') + '> Reveal on click only</label>';
                        
                        var _scrnRvDepthFamily = ['z_depth','depth_spring','depth_vortex','depth_zoom'].indexOf(_scrnRv) !== -1;
                        html += '<div class="impulse-margin-grid impulse-z-depth-options" style="display:' + (_scrnRvDepthFamily ? 'grid' : 'none') + ';margin-bottom:10px">';
                        html += settingSliderR('screen_intensity', 'Depth', settings, 50, 0, 100, '%');
                        html += '</div>';

                        html += '<div class="impulse-margin-grid" style="margin-bottom:10px">';
                        html += settingSliderR('screen_speed', 'Speed', settings, 76, 0, 100, '%');
                        html += settingSliderR('screen_sensitivity', 'Sensitivity', settings, 1, 1, 4, '');
                        html += '</div>';
                        html += '</div>'; 
                    }

                    

                    var fwChecked = settings.full_width === '1' || settings.full_width === 1 || settings.full_width === true;
                    var cmpChecked = settings.compact === '1' || settings.compact === 1 || settings.compact === true;
                    var frostedChecked = settings.frosted_glass === '1' || settings.frosted_glass === 1 || settings.frosted_glass === true;
                    html += '<div style="margin-bottom:8px">';

                    if (!isRootScreen) {
                        html += '<label style="display:block;font-size:11px;color:'+ImpC.muted+';margin-bottom:4px">Width</label>';
                        html += '<label style="display:flex;align-items:center;gap:6px;height:26px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;white-space:nowrap"><input type="checkbox" name="full_width" value="1"' + (fwChecked ? ' checked' : '') + '> Ignore page max-width</label>';
                    }

                    
                    html += '<label style="display:flex;align-items:center;gap:6px;height:26px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;white-space:nowrap"><input type="checkbox" name="compact" value="1"' + (cmpChecked ? ' checked' : '') + '> Compact (hug content)</label>';
                    html += '<label class="impulse-section-frosted-wrap" style="display:' + (cmpChecked ? 'flex' : 'none') + ';align-items:center;gap:6px;height:26px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;white-space:nowrap"><input type="checkbox" name="frosted_glass" value="1"' + (frostedChecked ? ' checked' : '') + '> Frosted glass</label>';
                    html += '</div>';

                    

                    

                    
                    
                    html += '<div class="impulse-margin-grid">';
                    if (cmpChecked) {
                        html += settingSliderR('compact_max_width', 'Width', settings, 800, 240, 1440, 'px', true);
                    } else {
                        html += settingSliderR('content_width', 'Content Width', settings, 100, 20, 100, '%');
                    }
                    html += settingSliderR('item_space', 'Content Gap', settings, 0, 0, 80, 'px', true);

                    

                    

                    

                    var _frostShow = (cmpChecked && frostedChecked) ? 'contents' : 'none';
                    html += '<div class="impulse-section-frosted-tune" style="display:' + _frostShow + '">';
                    html += settingSliderR('frosted_blur', 'Blur', settings, 20, 4, 40, 'px');
                    html += '</div>';
                    html += '<div class="impulse-section-frosted-tune" style="display:' + _frostShow + '">';
                    html += settingSliderR('border_radius', 'Corners', settings, 0, 0, 30, 'px');
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('padding_top', 'Padding Top', settings, 20, 0, 200, 'px', true);
                    html += settingSliderR('padding_bottom', 'Padding Bottom', settings, 20, 0, 200, 'px', true);
                    html += settingSliderR('padding_left', 'Padding Left', settings, 20, 0, 200, 'px', true);
                    html += settingSliderR('padding_right', 'Padding Right', settings, 20, 0, 200, 'px', true);
                    html += '</div>';

                    

                    

                    
                    html += '<div class="impulse-section-min-height-wrap"' + (isRootScreen ? ' style="display:none"' : '') + '>';
                    var _legacyHasMH = (settings.min_height !== undefined && settings.min_height !== null && settings.min_height !== '');
                    var _hMode = settings.height_mode || (_legacyHasMH ? 'vh' : 'auto');
                    html += '<label style="font-size:11px;color:#888;display:block;margin-bottom:4px">Height Mode</label>';
                    html += '<div class="impulse-btn-group" data-name="height_mode" style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px;margin-bottom:8px">';
                    [['auto','Auto'],['vh','Min vh'],['aspect','Aspect'],['px','Fixed px']].forEach(function(opt){
                        var active = _hMode === opt[0] ? ' active' : '';
                        html += '<button type="button" class="' + active.trim() + '" data-value="' + opt[0] + '" style="height:26px;font-size:11px;padding:0">' + opt[1] + '</button>';
                    });
                    html += '<input type="hidden" name="height_mode" value="' + _hMode + '">';
                    html += '</div>';
                    
                    html += '<div class="impulse-section-height-vh-wrap" style="display:' + (_hMode === 'vh' ? 'block' : 'none') + '">';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('min_height', 'Min Height', settings, 60, 0, 100, 'vh');
                    html += '</div></div>';
                    html += '<div class="impulse-section-height-aspect-wrap" style="display:' + (_hMode === 'aspect' ? 'block' : 'none') + ';margin-bottom:8px">';
                    var _ar = settings.aspect_ratio || '16:9';
                    html += '<label style="font-size:11px;color:#888;display:block;margin-bottom:4px">Aspect Ratio</label>';
                    html += '<div class="impulse-btn-group" data-name="aspect_ratio" style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px">';
                    ['16:9','21:9','4:3','1:1'].forEach(function(r){
                        var active = _ar === r ? ' active' : '';
                        html += '<button type="button" class="' + active.trim() + '" data-value="' + r + '" style="height:26px;font-size:11px;padding:0">' + r + '</button>';
                    });
                    html += '<input type="hidden" name="aspect_ratio" value="' + _ar + '">';
                    html += '</div></div>';
                    html += '<div class="impulse-section-height-px-wrap" style="display:' + (_hMode === 'px' ? 'block' : 'none') + '">';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('height_px', 'Height', settings, 600, 100, 2000, 'px');
                    html += '</div></div>';
                    html += '</div>';
                    
                    html += '<div class="impulse-section-divider">Alignment</div>';
                    
                    var curCA = settings.content_align || 'center';
                    
                    if (curCA === 'flex-start') curCA = 'left';
                    if (curCA === 'flex-end') curCA = 'right';

                    
                    var _vaPageDefault = (window.Impulse && Impulse.pageSettings && Impulse.pageSettings.body_scroll === 'classic') ? 'top' : 'center';
                    var curVA = settings.valign || _vaPageDefault;
                    var isSpread = (curVA === 'between' || curVA === 'around' || curVA === 'evenly');
                    var colMap = ['left','center','right'];
                    var rowMap = ['top','center','bottom'];
                    html += '<div style="display:flex;align-items:center;gap:12px">';
                    html += '<div class="impulse-align-grid" data-name="align_grid">';
                    for (var r = 0; r < 3; r++) {
                        for (var c = 0; c < 3; c++) {
                            var dotCA = colMap[c];
                            var dotVA = rowMap[r];
                            var isActive = !isSpread && curCA === dotCA && curVA === dotVA;
                            var isColActive = isSpread && curCA === dotCA;
                            var cls = 'impulse-align-dot' + (isActive ? ' active' : '') + (isColActive ? ' col-active' : '');
                            html += '<button type="button" class="' + cls + '" data-ca="' + dotCA + '" data-va="' + dotVA + '"></button>';
                        }
                    }
                    html += '</div>';
                    html += '<div style="display:flex;flex-direction:column;justify-content:flex-end;align-self:stretch;flex:1">';
                    html += '<button type="button" class="impulse-spread-btn' + (isSpread ? ' active' : '') + '" style="height:26px;font-size:11px;padding:0 10px;border-radius:3px;border:1px solid '+ImpC.border+';background:' + (isSpread ? ''+ImpC.text+'' : ''+ImpC.border+'') + ';color:' + (isSpread ? ''+ImpC.surface2+'' : ''+ImpC.muted+'') + ';cursor:pointer;white-space:nowrap;box-sizing:border-box">Spread</button>';
                    html += '</div>';
                    html += '</div>';

                    var _sectDevSfx = (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '';
                    html += '<input type="hidden" name="content_align' + _sectDevSfx + '" value="' + curCA + '">';

                    
                    
                    html += '<input type="hidden" name="valign' + _sectDevSfx + '" value="' + curVA + '" data-impulse-default="' + _vaPageDefault + '">';

                    

                    

                    html += '<div class="impulse-section-divider impulse-divider-with-toggle">';
                    html +=     '<span>Background</span>';
                    html +=     '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                    html +=     '<div class="impulse-bg-base-color-wrap" style="display:' + (_bgCovers ? 'none' : 'flex') + ';align-items:center;gap:5px;flex-shrink:0">';
                    html +=         '<span style="font-size:10px;letter-spacing:.04em;color:#888;text-transform:uppercase">Base</span>';

                    

                    

                    

                    

                    var _mbEffBase = '#0a0c12';
                    (function(){
                        var _b1 = (settings.bg_color || '').trim();
                        if (!_b1 || _b1 === 'transparent') return;
                        var _hx = /^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(_b1);
                        var _op = false;
                        if (_hx) { _op = !_hx[2] || parseInt(_hx[2],16) >= 242; }
                        else if (/^#[0-9a-fA-F]{3}$/.test(_b1)) { _op = true; }
                        else { var _rm = /rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([\d.]+))?\s*\)/i.exec(_b1); _op = _rm ? (_rm[1] === undefined || _rm[1] === '' || parseFloat(_rm[1]) >= 0.95) : true; }
                        if (_op) _mbEffBase = _b1;
                    })();
                    html +=         settingColorSwatchOnly('mesh_base_color', settings.mesh_base_color || '', 'Base colour', _mbEffBase);
                    html +=     '</div>';
                    html += '</div>';

                    html += '<div class="impulse-bg-no-image-row" style="display:' + (_bgCovers ? 'none' : 'flex') + ';align-items:center;justify-content:space-between;gap:6px">';

                    

                    

                    
                    html += '<div style="display:flex;align-items:center;gap:5px">';
                    html +=     settingColorSwatchOnly('bg_color',   settings.bg_color   || 'transparent');
                    html +=     settingColorSwatchOnly('bg_color_2', settings.bg_color_2 || '');
                    html +=     settingColorSwatchOnly('bg_color_3', settings.bg_color_3 || '');
                    html +=     settingColorSwatchOnly('bg_color_4', settings.bg_color_4 || '');
                    html += '</div>';

                    

                    

                    

                    

                    
                    var _bg3dIsClassic = !!(window.Impulse && Impulse.pageSettings && Impulse.pageSettings.body_scroll === 'classic');
                    html += '<div style="display:flex;align-items:center;gap:5px;flex-shrink:0">';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-select-section-bg" style="white-space:nowrap;height:26px;line-height:24px;padding:0 10px;box-sizing:border-box">Image</button>';
                    if (_bg3dIsClassic) {
                        html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-bg-3d-pick-direct" title="Pick a 3D depth image" style="white-space:nowrap;height:26px;line-height:24px;padding:0 10px;box-sizing:border-box">3D</button>';
                    }
                    html += '</div>';
                    html += '</div>';
                    html += '<input type="hidden" name="bg_image" value="' + (hasBgImage) + '">';

                    
                    var _hasMesh = (function(){
                        var ks = ['bg_color_2','bg_color_3','bg_color_4'];
                        for (var i=0;i<ks.length;i++) {
                            var v = settings[ks[i]] || '';
                            if (v && v !== '' && v !== 'transparent' && v.indexOf('rgba(0,0,0,0)') !== 0) return true;
                        }
                        return false;
                    })();
                    html += '<div class="impulse-section-mesh-wrap" style="display:' + (_hasMesh ? 'block' : 'none') + ';margin-top:6px">';
                    html += '<div class="impulse-margin-grid">';

                    

                    
                    
                    html += settingSliderR('bg_mesh_speed', 'Speed',   settings, 7,   0, 10,  '');
                    html += settingSliderR('bg_mesh_alpha', 'Opacity', settings, 100, 0, 100, '%');
                    html += '</div>'; 

                    

                    
                    var _slotKeys  = ['bg_color', 'bg_color_2', 'bg_color_3', 'bg_color_4'];
                    var _slotDefXY = [[10,10], [90,10], [10,90], [90,90]];
                    _slotKeys.forEach(function (sk, i) {
                        var bx = settings[sk + '_x'];
                        var by = settings[sk + '_y'];
                        if (bx === undefined || bx === '') bx = _slotDefXY[i][0];
                        if (by === undefined || by === '') by = _slotDefXY[i][1];
                        html += '<input type="hidden" name="' + sk + '_x" value="' + bx + '">';
                        html += '<input type="hidden" name="' + sk + '_y" value="' + by + '">';
                    });
                    html += '</div>';
                    var bgDevice = window.impulseDevice || 'desktop';

                    

                    

                    var _bgPreviewImg = hasBgImage || settings.bg_depth_image || '';
                    if (_bgPreviewImg) {
                        var bgPos = (bgDevice !== 'desktop' && settings['bg_position_' + bgDevice]) ? settings['bg_position_' + bgDevice] : (settings.bg_position || '50% 50%');
                        var bgSizeVal = (bgDevice !== 'desktop' && settings['bg_size_' + bgDevice]) ? settings['bg_size_' + bgDevice] : (settings.bg_size || 'cover');
                        var showDots = true;
                        html += '<div id="impulse-section-bg-preview" title="Click to replace" style="position:relative;cursor:pointer">';
                        html += '<img src="' + _bgPreviewImg + '" class="impulse-bg-image-thumb" style="width:100%;max-height:80px;object-fit:cover;border-radius:4px;display:block">';
                        html += '<button type="button" class="impulse-remove-bg" style="position:absolute;top:4px;right:4px;z-index:2;width:26px;height:26px;border-radius:3px;border:none;background:rgba(0,0,0,0.6);color:'+ImpC.white+';cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove image"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        
                        html += '<div class="impulse-bg-position-grid" style="position:absolute;top:0;left:0;right:0;bottom:0;display:' + (showDots ? 'grid' : 'none') + ';grid-template-columns:repeat(3,1fr);grid-template-rows:repeat(3,1fr);padding:4px;pointer-events:none">';
                        var posMap = [
                            {v:'0% 0%',icon:'<path d="M7 17V7h10"/><path d="M17 17 7 7"/>'},
                            {v:'50% 0%',icon:'<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>'},
                            {v:'100% 0%',icon:'<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'},
                            {v:'0% 50%',icon:'<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>'},
                            {v:'50% 50%',icon:'<path d="m7 20 5-5 5 5"/><path d="m7 4 5 5 5-5"/>'},
                            {v:'100% 50%',icon:'<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>'},
                            {v:'0% 100%',icon:'<path d="M17 7 7 17"/><path d="M17 17H7V7"/>'},
                            {v:'50% 100%',icon:'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'},
                            {v:'100% 100%',icon:'<path d="m7 7 10 10"/><path d="M17 7v10H7"/>'}
                        ];
                        var alignMap = ['flex-start','center','flex-end'];
                        posMap.forEach(function(p, i) {
                            var isActive = bgPos === p.v;
                            var row = Math.floor(i / 3);
                            var col = i % 3;
                            html += '<div style="display:flex;align-items:' + alignMap[row] + ';justify-content:' + alignMap[col] + ';pointer-events:auto">';
                            html += '<button type="button" class="impulse-bg-pos-btn' + (isActive ? ' active' : '') + '" data-pos="' + p.v + '" style="width:18px;height:18px;border-radius:3px;border:none;background:' + (isActive ? 'rgba(255,255,255,0.5)' : 'rgba(128,128,128,0.25)') + ';cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center;mix-blend-mode:difference" title="' + p.v + '"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:difference">' + p.icon + '</svg></button>';
                            html += '</div>';
                        });
                        html += '</div>';
                        html += '<input type="hidden" name="bg_position" value="' + bgPos + '">';
                        html += '</div>';
                    }

                    

                    var _hasBgOrDepth = !!(hasBgImage || (settings.bg_depth_image && settings.bg_depth_map));
                    html += '<div class="impulse-bg-image-settings" style="display:' + (_hasBgOrDepth ? 'block' : 'none') + '">';
                    
                    var bgSizeResolved = (bgDevice !== 'desktop' && settings['bg_size_' + bgDevice]) ? settings['bg_size_' + bgDevice] : (settings.bg_size || 'cover');
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="bg_size" style="display:flex;width:100%;gap:3px;margin-top:6px">';
                    html += '<button type="button" data-value="cover"' + (bgSizeResolved === 'cover' ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Cover</button>';
                    html += '<button type="button" data-value="contain"' + (bgSizeResolved === 'contain' ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Contain</button>';
                    html += '<input type="hidden" name="bg_size" value="' + bgSizeResolved + '">';
                    html += '</div>';

                    

                    

                    

                    

                    

                    

                    html += '<input type="hidden" name="bg_depth_image" value="' + escapeHtml(settings.bg_depth_image || '') + '">';
                    html += '<input type="hidden" name="bg_depth_map"   value="' + escapeHtml(settings.bg_depth_map   || '') + '">';

                    

                    

                    var _bgIsClassicScroll = !!(window.Impulse && Impulse.pageSettings && Impulse.pageSettings.body_scroll === 'classic');
                    if (_bgIsClassicScroll) {
                        html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                        html += settingSliderR('bg_depth_strength', '3D depth', settings, 0, 0, 100, '%');
                        html += '<div></div>';
                        html += '</div>';
                    }

                    html += '</div>';

                    

                    

                    

                    
                    (function () {
                        var _legOp = parseFloat(settings.overlay_opacity);
                        if (isNaN(_legOp) || _legOp <= 0) return;
                        if (settings.gradient_overlay_color1 || settings.gradient_overlay_color2) return;
                        var _legCol = (settings.overlay_color || '#000000').trim();
                        var _rgba = '';
                        var _alpha = _legOp / 100;
                        var _rm = _legCol.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);
                        if (_rm) {
                            _rgba = 'rgba(' + _rm[1] + ',' + _rm[2] + ',' + _rm[3] + ',' + _alpha + ')';
                        } else if (_legCol.charAt(0) === '#') {
                            var _h = _legCol.length === 4
                                ? '#' + _legCol[1] + _legCol[1] + _legCol[2] + _legCol[2] + _legCol[3] + _legCol[3]
                                : _legCol;
                            var _r = parseInt(_h.substr(1, 2), 16);
                            var _g = parseInt(_h.substr(3, 2), 16);
                            var _b = parseInt(_h.substr(5, 2), 16);
                            if (!isNaN(_r) && !isNaN(_g) && !isNaN(_b)) {
                                _rgba = 'rgba(' + _r + ',' + _g + ',' + _b + ',' + _alpha + ')';
                            }
                        }
                        if (!_rgba) return;
                        settings.gradient_overlay_color1 = _rgba;
                        settings.gradient_overlay_color2 = _rgba;
                        settings.overlay_color = '';
                        settings.overlay_opacity = 0;
                    })();

                    

                    

                    
                    {
                        var _goColor1 = settings.gradient_overlay_color1 || 'rgba(0,0,0,0)';
                        var _goColor2 = settings.gradient_overlay_color2 || 'rgba(0,0,0,0)';
                        var _goType = (settings.gradient_overlay_type === 'linear') ? 'linear' : 'radial';

                        
                        
                        var _goAlive = (function (c1, c2) {
                            var alive = function (c) {
                                if (!c || c === 'transparent') return false;
                                if (c.indexOf('rgba(0,0,0,0)') === 0) return false;
                                return true;
                            };
                            return alive(c1) || alive(c2);
                        })(_goColor1, _goColor2);

                        

                        
                        
                        html += '<div class="impulse-section-overlay-wrap">';
                        html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:10px">';
                        html += '<span>Overlay</span>';
                        html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                        html += '<div style="display:flex;align-items:center;gap:5px;flex-shrink:0">';
                        html +=     settingColorSwatchOnly('gradient_overlay_color1', _goColor1, 'Center color');
                        html +=     settingColorSwap('gradient_overlay_color1', 'gradient_overlay_color2', 'Swap center ↔ edge');
                        html +=     settingColorSwatchOnly('gradient_overlay_color2', _goColor2, 'Edge color');
                        html += '</div>';
                        html += '</div>';
                        html += '<div class="impulse-section-overlay-sliders" style="display:' + (_goAlive ? 'block' : 'none') + '">';

                        
                        
                        html += '<div class="impulse-btn-group" data-name="gradient_overlay_type" style="display:grid;grid-template-columns:repeat(2,1fr);gap:3px;margin:2px 0 8px">';
                        html += '<button type="button" class="' + (_goType === 'radial' ? 'active' : '') + '" data-value="radial" style="height:26px;font-size:11px;padding:0">Radial</button>';
                        html += '<button type="button" class="' + (_goType === 'linear' ? 'active' : '') + '" data-value="linear" style="height:26px;font-size:11px;padding:0">Linear</button>';
                        html += '<input type="hidden" name="gradient_overlay_type" value="' + _goType + '">';
                        html += '</div>';
                        html += '<div class="impulse-margin-grid">';
                        html += settingSliderR('gradient_overlay_diameter',  'Diameter',  settings, 100, 10, 200, '%');
                        html += '<div class="impulse-go-roundness-wrap" style="display:' + (_goType === 'linear' ? 'none' : 'contents') + '">';
                        html += settingSliderR('gradient_overlay_roundness', 'Roundness', settings, 100, 0,  100, '%');
                        html += '</div>';
                        html += settingSliderR('gradient_overlay_angle',     'Angle',     settings, 0,   0,  360, '°');
                        html += settingSliderR('gradient_overlay_softness',  'Softness',  settings, 100, 0,  100, '%');
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
                    }

                    var bgVideoUrl = settings.bg_video || '';
                    var bgVideoFallback = settings.bg_video_fallback || '';
                    html += '<div class="impulse-section-divider" style="margin-top:10px">Video Background</div>';

                    
                    
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:5px;margin-top:6px">';
                    html += '<input type="text" name="bg_video" value="' + escapeHtml(bgVideoUrl) + '" placeholder="https://..." style="height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box;min-width:0">';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-select-section-bg-video" style="height:26px;padding:0;font-size:11px">Select File</button>';
                    html += '</div>';
                    
                    html += '<div class="impulse-bg-video-fallback-row" style="display:' + (bgVideoUrl ? 'grid' : 'none') + ';grid-template-columns:1fr 1fr;gap:5px;margin-top:6px;align-items:center">';
                    html += '<span style="font-size:11px;color:'+ImpC.muted+'">Poster / Fallback</span>';
                    if (bgVideoFallback) {
                        html += '<div style="position:relative;display:flex;align-items:center;gap:4px">';
                        html += '<img src="' + escapeHtml(bgVideoFallback) + '" style="height:26px;width:auto;max-width:60px;object-fit:cover;border-radius:3px;display:block;border:1px solid '+ImpC.border+'">';
                        html += '<button type="button" class="impulse-remove-section-bg-fallback" style="width:26px;height:26px;border-radius:50%;border:none;background:'+ImpC.dim+';color:'+ImpC.white+';cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;font-size:9px;flex-shrink:0" title="Remove">×</button>';
                        html += '</div>';
                    } else {
                        html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-select-section-bg-fallback" style="height:26px;padding:0;font-size:11px">Select Image</button>';
                    }
                    html += '</div>';
                    html += '<input type="hidden" name="bg_video_fallback" value="' + escapeHtml(bgVideoFallback) + '">';
                    html += '<p class="impulse-setting-hint" style="margin-top:6px">Autoplays silently. Poster shown on mobile.</p>';

                    

                    
                    if (!$('.impulse-panel-right').data('parent-id')) {
                        var _twMotionRaw = String(settings.tw_motion || 'none').toLowerCase();
                        var _twSpotlight = (settings.tw_spotlight === '1' || settings.tw_spotlight === 1 || settings.tw_spotlight === true);
                        var _twParallax = (settings.tw_parallax === '1' || settings.tw_parallax === 1 || settings.tw_parallax === true);
                        if (_twMotionRaw === 'wave' || _twMotionRaw === 'perspective') { _twMotionRaw = 'none'; } 
                        var _twMotion = (['scroll', 'drift'].indexOf(_twMotionRaw) !== -1) ? _twMotionRaw : 'none';
                        var _twSpace = (settings.tw_space != null && settings.tw_space !== '') ? parseInt(settings.tw_space, 10) : 24;
                        var _twSize = parseInt(settings.tw_size, 10) || 72;
                        var _twGap = parseInt(settings.tw_gap, 10) || 0;
                        var _twSpeed = (settings.tw_speed != null && settings.tw_speed !== '') ? parseFloat(settings.tw_speed) : 1;
                        var _twColor = settings.tw_color || 'rgba(255,255,255,0.14)';
                        var _twWeight = String(settings.tw_weight || '800');
                        var _twSpotSize = (settings.tw_spot_size != null && settings.tw_spot_size !== '') ? parseInt(settings.tw_spot_size, 10) : 600;
                        
                        var _twOn = (settings.tw_on === undefined || settings.tw_on === null) ? true
                                  : (settings.tw_on === '1' || settings.tw_on === 1 || settings.tw_on === true);
                        html += '<div class="impulse-section-divider impulse-collapsible-divider" data-target="impulse-textwall-content" style="cursor:pointer;margin-top:12px;display:flex;align-items:center;gap:6px">';
                        html +=   '<span>Text Wall</span>';
                        html +=   '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                        html +=   '<label class="impulse-tw-on-wrap impulse-tip-left" data-tip="Show text wall" style="flex-shrink:0;display:flex;align-items:center;margin:0" onclick="event.stopPropagation()" onmousedown="event.stopPropagation()"><input type="checkbox" name="tw_on" value="1" class="impulse-autosave"' + (_twOn ? ' checked' : '') + ' style="margin:0"></label>';
                        html +=   '<span class="impulse-tw-color-wrap" style="flex-shrink:0;display:flex" onclick="event.stopPropagation()" onmousedown="event.stopPropagation()">' + settingColorSwatchOnly('tw_color', _twColor, 'Text colour') + '</span>';
                        html += '</div>';
                        html += '<div class="impulse-textwall-content">';
                        html += '<p class="impulse-setting-hint" style="margin-top:2px">One line, cloned to fill this section behind your content. Classic-scroll pages only.</p>';
                        html += '<input type="text" name="tw_text" class="impulse-autosave" value="' + escapeHtml(settings.tw_text || '') + '" placeholder="Repeated line (e.g. SNACKS)" style="width:100%;height:26px;padding:0 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;box-sizing:border-box;margin-bottom:6px">';
                        html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:5px;margin-bottom:6px">';
                        html += '<select name="tw_motion" class="impulse-autosave impulse-sel" style="height:26px;font-size:11px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';box-sizing:border-box">';
                        [['none', 'None'], ['scroll', 'Scroll'], ['drift', 'Drift']].forEach(function (m) { html += '<option value="' + m[0] + '"' + (_twMotion === m[0] ? ' selected' : '') + '>' + m[1] + '</option>'; });
                        html += '</select>';
                        html += '<select name="tw_weight" class="impulse-autosave impulse-sel" style="height:26px;font-size:11px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';box-sizing:border-box">';
                        [['300', 'Light'], ['400', 'Regular'], ['600', 'Semibold'], ['700', 'Bold'], ['800', 'Heavy'], ['900', 'Black']].forEach(function (w) { html += '<option value="' + w[0] + '"' + (_twWeight === w[0] ? ' selected' : '') + '>' + w[1] + '</option>'; });
                        html += '</select>';
                        html += '</div>';
                        html += '<label class="impulse-inline-right" style="display:flex;align-items:center;justify-content:space-between;margin:0 0 4px"><span style="font-size:11px">Spotlight</span><input type="checkbox" name="tw_spotlight" value="1" class="impulse-autosave"' + (_twSpotlight ? ' checked' : '') + '></label>';
                        html += '<div class="impulse-tw-spot-diam" style="display:' + (_twSpotlight ? 'block' : 'none') + ';margin:0 0 4px">' + settingSlider('tw_spot_size', 'Diameter', _twSpotSize, 200, 1600, 'px', false, true, 600, false, 20) + '</div>';
                        html += '<label class="impulse-inline-right" style="display:flex;align-items:center;justify-content:space-between;margin:0 0 6px"><span style="font-size:11px">Mouse parallax</span><input type="checkbox" name="tw_parallax" value="1" class="impulse-autosave"' + (_twParallax ? ' checked' : '') + '></label>';
                        html += '<div class="impulse-margin-grid">';
                        html += settingSlider('tw_size', 'Size', _twSize, 20, 220, 'px', false, true, 72, false, 2);
                        html += settingSlider('tw_space', 'Space', _twSpace, 0, 160, 'px', false, true, 24, false, 2);
                        html += '</div>';
                        html += '<div class="impulse-margin-grid">';
                        html += settingSlider('tw_gap', 'Row gap', _twGap, 0, 80, 'px', false, true, 0, false, 1);
                        html += settingSlider('tw_speed', 'Speed', _twSpeed, 0.25, 3, 'x', false, true, 1, false, 0.25);
                        html += '</div>';

                        html += '</div>';
                    }

                    

                    

                    
                    html += '<div class="impulse-section-divider impulse-collapsible-divider" data-target="impulse-visibility-content" style="cursor:pointer"><span>Visibility</span></div>';
                    html += '<div class="impulse-visibility-content">';
                    html += settingVisibility(settings);
                    html += '</div>';

                    
                    html += settingBgShapes(settings);

                    

                        
                        var sTilt = getResponsiveValue(settings, 'section_tilt', '') ? '1' : '';
                        html += '<div class="impulse-section-divider impulse-divider-with-toggle">';
                        html += '<span>Tilt</span>';
                        html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                        html += '<input type="checkbox" name="section_tilt" value="1"' + (sTilt === '1' ? ' checked' : '') + '>';
                        html += '</div>';
                        html += '<div class="impulse-section-tilt-settings" style="display:' + (sTilt === '1' ? 'block' : 'none') + '">';
                        html += '<div class="impulse-margin-grid">';
                        html += settingSliderR('section_tilt_intensity', 'Intensity', settings, 50, 0, 100, '%');
                        html += '</div>';
                        html += '</div>';

                        html += '<div class="impulse-section-divider">Ambient</div>';
                        var sAmb = getResponsiveValue(settings, 'section_ambient', 'none') || 'none';
                        html += '<div class="impulse-setting-row">';
                        html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="section_ambient" data-toggleable="1" style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px">';
                        var ambPresets = [
                            {v:'float',l:'Float'},   {v:'shine',l:'Shine'},     {v:'ripple',l:'Ripple'}, {v:'glitch',l:'Glitch'},
                            {v:'pulse',l:'Pulse'},   {v:'prism',l:'Prism'},     {v:'aurora',l:'Aurora'}, {v:'spotlight',l:'Spotlight'}
                        ];
                        ambPresets.forEach(function(p) {
                            var pl = window.isProEffect && window.isProEffect('sectionMotion', p.v);
                            var lockA = pl ? ' data-pro-locked="1" data-pro-label="' + p.l + ' motion preset"' : '';
                            var lockC = pl ? ' impulse-pro-locked' : '';
                            html += '<button type="button" data-value="' + p.v + '" class="' + (sAmb === p.v ? 'active' : '') + lockC + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box"' + lockA + '>' + p.l + '</button>';
                        });
                        html += '<input type="hidden" name="section_ambient" value="' + sAmb + '">';
                        html += '</div></div>';
                        html += '<div class="impulse-section-ambient-settings" style="display:' + (sAmb !== 'none' ? 'block' : 'none') + '">';

                        
                        html += '<div class="impulse-margin-grid">';
                        html += settingSliderR('section_ambient_intensity', 'Intensity', settings, 50, 0, 100, '%');
                        
                        var sAmbHue = getResponsiveValue(settings, 'section_ambient_hue', 200);
                        var _hueEffects = (sAmb === 'pulse' || sAmb === 'spotlight' || sAmb === 'aurora');

                        
                        
                        html += '<div class="impulse-setting-row inline-slider impulse-hue-slider impulse-section-ambient-hue-wrap" data-responsive="true" style="display:' + (_hueEffects ? 'grid' : 'none') + '">';
                        html += '<label>Hue</label>';
                        html += '<span class="impulse-slider-value">' + sAmbHue + '°</span>';
                        html += '<div class="impulse-slider-row" data-unit="°" data-responsive="true">';
                        html += '<input type="range" name="section_ambient_hue" value="' + sAmbHue + '" min="0" max="360" data-default="200">';
                        html += '</div>';
                        html += '</div>';

                        
                        var sAmbOver = !!getResponsiveValue(settings, 'section_ambient_over_content', false);
                        var _overEffects = (sAmb === 'shine' || sAmb === 'pulse' || sAmb === 'prism' || sAmb === 'aurora' || sAmb === 'spotlight');
                        html += '<div class="impulse-setting-row inline-slider impulse-section-ambient-over-wrap" data-responsive="true" style="grid-column:2;justify-content:flex-end;display:' + (_overEffects ? 'flex' : 'none') + '">';
                        html += '<label style="white-space:nowrap">Over content</label>';
                        html += '<div class="impulse-slider-row" style="justify-content:flex-end">';
                        html += '<input type="checkbox" name="section_ambient_over_content" value="1"' + (sAmbOver ? ' checked' : '') + '>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';

                    
                    
                    {

                        

                        html += '<div class="impulse-section-divider">3D Reveal</div>';
                        var _ovfxSel = getResponsiveValue(settings, 'ovfx', '') || '';
                        html += '<div class="impulse-setting-row">';
                        html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="ovfx" data-toggleable="1" style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px">';
                        OVFX_PRESETS.forEach(function(p) {
                            html += '<button type="button" data-value="' + p.v + '" class="' + (_ovfxSel === p.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + p.l + '</button>';
                        });
                        html += '<input type="hidden" name="ovfx" value="' + _ovfxSel + '">';
                        html += '</div></div>';
                        html += '<div class="impulse-ovfx-settings" style="display:' + (_ovfxSel ? 'block' : 'none') + '">';
                        
                        var _ovIsFlat = OVFX_FLAT.indexOf(_ovfxSel) !== -1;
                        html += '<div class="impulse-ovfx-swatches" style="display:' + (_ovIsFlat ? 'grid' : 'none') + ';grid-template-columns:1fr 1fr;align-items:end;column-gap:6px;margin-top:8px">';
                        html += '<div style="display:flex;flex-direction:column;align-items:flex-start;gap:5px"><label style="font-size:11px;color:' + ImpC.muted + ';line-height:1">Color 1</label><div class="impulse-setting-row" style="margin:0">' + settingColorSwatchOnly('ovfx_c1', settings.ovfx_c1 || '#1d2327') + '</div></div>';
                        html += '<div style="display:flex;flex-direction:column;align-items:flex-end;gap:5px"><label style="font-size:11px;color:' + ImpC.muted + ';line-height:1">Color 2</label><div class="impulse-setting-row" style="margin:0">' + settingColorSwatchOnly('ovfx_c2', settings.ovfx_c2 || '#f5f5f5') + '</div></div>';
                        html += '</div>';
                        html += '<div class="impulse-ovfx-sliders impulse-margin-grid" style="margin-top:8px">';
                        html += buildOvfxSliders(_ovfxSel || 'noise', settings);
                        html += '</div>';
                        var _ovEase = getResponsiveValue(settings, 'ovfx_ease', 'spring') || 'spring';
                        html += '<div style="margin-top:8px"><label style="font-size:11px;color:' + ImpC.muted + ';display:block;margin-bottom:4px">Easing</label>';
                        html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="ovfx_ease" style="display:grid;grid-template-columns:repeat(3,1fr);gap:3px">';
                        [['glide', 'Glide'], ['snap', 'Snap'], ['spring', 'Spring']].forEach(function(e) {
                            html += '<button type="button" data-value="' + e[0] + '" class="' + (_ovEase === e[0] ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">' + e[1] + '</button>';
                        });
                        html += '<input type="hidden" name="ovfx_ease" value="' + _ovEase + '">';
                        html += '</div></div>';
                        html += '</div>';
                    }

                    

                    

                    

                    

                    

                    
                    if (isRootScreen) {
                        html += '<div class="impulse-section-divider" style="margin-top:18px"><span>Scroll Timeline</span><span style="flex:1;height:1px;background:' + ImpC.panel + '"></span></div>';

                        var _apSecs = parseFloat(settings.screen_autoplay_seconds);
                        if (!isFinite(_apSecs) || _apSecs < 0) _apSecs = 0;
                        var _apOn = _apSecs > 0;
                        html += '<div style="display:flex;align-items:center;gap:8px;margin:8px 0 12px 0;font-size:11px;color:' + ImpC.muted + '">';
                        
                        html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer;margin:0">';
                        html += '<input type="checkbox" name="_screen_autoplay_on_ui" value="1"' + (_apOn ? ' checked' : '') + '>';
                        html += 'Auto-advance after';
                        html += '</label>';
                        
                        html += '<input type="text" inputmode="decimal" name="screen_autoplay_seconds" class="impulse-autosave" maxlength="4" value="' + (_apOn ? _apSecs : '') + '" placeholder="5" style="width:30px;height:24px;padding:2px 4px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;font-family:inherit;box-sizing:border-box;text-align:center"' + (_apOn ? '' : ' disabled') + '>';
                        html += '<span>seconds</span>';
                        html += '</div>';
                        
                        html += '<label style="display:flex;align-items:center;gap:8px;margin:0 0 12px 0;font-size:11px;color:' + ImpC.muted + ';cursor:pointer">';
                        html += '<input type="checkbox" name="screen_show_scroll" class="impulse-autosave" value="1"' + (settings.screen_show_scroll ? ' checked' : '') + '>';
                        html += '<span>Show scroll cue (chevron at bottom)</span>';
                        html += '</label>';
                        
                        html += '<label style="display:flex;align-items:center;gap:8px;margin:0 0 12px 0;font-size:11px;color:' + ImpC.muted + ';cursor:pointer">';
                        html += '<input type="checkbox" name="screen_hide_effect" class="impulse-autosave" value="1"' + (settings.screen_hide_effect ? ' checked' : '') + '>';
                        html += '<span>Hide background effect on this screen</span>';
                        html += '</label>';
                        
                        html += '<div style="display:flex;gap:8px;align-items:flex-start;padding:8px 10px;margin:-2px 0 12px 0;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-left:2px solid ' + ImpC.text + ';border-radius:3px;font-size:11px;line-height:1.45;color:' + ImpC.muted + '">'
                              +   '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;margin-top:1px;opacity:0.85"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'
                              +   '<span><strong style="color:' + ImpC.text + '">Live page only.</strong> The editor preview never auto-advances so you can keep authoring.</span>'
                              + '</div>';

                        html += '<div class="impulse-screen-bar-panel impulse-screen-bar-panel-timeline" data-tab="timeline" data-mount="section-panel"></div>';
                    }

                    html += '</div>'; 

                    html += '<div class="impulse-section-tab-content" data-stab="effects" style="display:none">';

                    

                    
                    var _animOn = getResponsiveValue(settings, 'bg_animation_enabled', false);
                    html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:0">';
                    html += '<span>Animation</span>';
                    html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                    html += '<input type="checkbox" name="bg_animation_enabled" value="1"' + (_animOn ? ' checked' : '') + '>';
                    html += '</div>';
                    html += '<div class="impulse-bg-animation-settings" style="display:' + (getResponsiveValue(settings, 'bg_animation_enabled', false) ? 'block' : 'none') + '">';

                    

                    var sectionAnimLayers = getResponsiveValue(settings, 'animation_layers', []);
                    if (typeof sectionAnimLayers === 'string') {
                        try { sectionAnimLayers = JSON.parse(sectionAnimLayers); } catch(e) { sectionAnimLayers = []; }
                    }
                    if (!Array.isArray(sectionAnimLayers)) sectionAnimLayers = [];
                    
                    html += '<input type="hidden" name="animation_layers" id="impulse-section-anim-layers-data" value=\'' + JSON.stringify(sectionAnimLayers).replace(/'/g, '&#39;') + '\'>';
                    html += '<div class="impulse-section-anim-layers-container">';
                    sectionAnimLayers.forEach(function(layer, idx) {
                        var ls = layer.settings || {};
                        var _layerVisible = layer._visible !== false; 
                        var isFirst = idx === 0;
                        html += '<div class="impulse-section-anim-layer' + (_layerVisible ? '' : ' impulse-anim-layer-hidden') + '" data-layer-index="' + idx + '" style="margin-bottom:6px">';
                        html += '<div class="impulse-section-anim-layer-header" style="display:flex;align-items:center;justify-content:space-between;padding:6px 0;cursor:pointer;border-bottom:1px solid '+ImpC.border+'">';
                        html += '<div style="display:flex;align-items:center;gap:8px">';
                        html += '<span class="impulse-section-anim-layer-drag" style="cursor: default;color:#666"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
                        html += '<span style="font-size:11px;color:'+ImpC.text+'">Layer ' + (idx + 1) + '</span>';
                        html += '</div>';

                        
                        html += '<div style="display:flex;align-items:center;gap:6px">';
                        html += '<button type="button" class="impulse-toolbox-btn impulse-toolbox-btn-delete impulse-section-anim-layer-delete" data-tip="Delete (right-click for more)"><svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>';
                        html += '<span class="impulse-section-anim-layer-toggle" style="color:#666;transition:transform 0.2s' + (isFirst ? '' : ';transform:rotate(-90deg)') + '"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg></span>';
                        html += '</div>';
                        html += '</div>';

                        html += '<div class="impulse-section-anim-layer-content" style="padding-top:8px;display:' + (isFirst ? 'block' : 'none') + '">';

                        var effects = [
                            { v: 'rings', l: 'Rings' },
                            { v: 'ring_trace', l: 'Ring Trace' },
                            { v: 'burst', l: 'Burst' },
                            { v: 'spiral', l: 'Spiral' },
                            { v: 'starburst', l: 'Starburst' },
                            { v: 'concentric', l: 'Concentric' },
                            { v: 'squares', l: 'Squares' },
                            { v: 'orbs', l: 'Orbs' },
                            { v: 'bokeh', l: 'Bokeh' },
                            { v: 'morphing', l: 'Morphing' },
                            { v: 'bubbles', l: 'Bubbles' },
                            { v: 'sine', l: 'Sine' },
                            { v: 'aurora', l: 'Aurora' },
                            { v: 'liquid', l: 'Liquid' },
                            { v: 'dot_matrix', l: 'Dot Matrix' },
                            { v: 'hex_grid', l: 'Hex Grid' },
                            { v: 'network', l: 'Network' },
                            { v: 'gradient', l: 'Gradient' },
                            { v: 'caustics', l: 'Caustics' },
                            { v: 'lava', l: 'Lava' }
                        ];
                        var currentEffect = layer.effect || '';
                        html += '<div class="impulse-section-anim-effect-grid" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-bottom:6px">';
                        effects.forEach(function(e) {
                            var isActive = currentEffect === e.v;
                            var pl = window.isProEffect && window.isProEffect('sectionAnims', e.v);
                            var lockA = pl ? ' data-pro-locked="1" data-pro-label="' + e.l + ' animation"' : '';
                            var lockC = pl ? ' impulse-pro-locked' : '';
                            html += '<button type="button" class="impulse-section-anim-effect-btn' + (isActive ? ' active' : '') + lockC + '" data-value="' + e.v + '" style="height:26px;padding:0 4px;font-size:10px;box-sizing:border-box;border:1px solid '+ImpC.border+';background:' + (isActive ? ''+ImpC.text+'' : ''+ImpC.panel+'') + ';color:' + (isActive ? ''+ImpC.surface2+'' : ''+ImpC.muted+'') + ';border-radius:3px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"' + lockA + '>' + e.l + '</button>';
                        });
                        html += '</div>';
                        html += '<input type="hidden" class="impulse-section-anim-layer-effect" value="' + currentEffect + '">';
                        
                        html += '<input type="hidden" class="impulse-section-anim-layer-blend" value="' + (layer.blend_mode || 'normal') + '">';
                        
                        html += '<div class="impulse-section-anim-effect-settings">';
                        html += buildBgEffectSettingsSimple(layer.effect || '', ls, layer.opacity, layer.z_index);
                        html += '</div>';
                        html += '</div>'; 
                        html += '</div>'; 
                    });
                    
                    html += '</div>'; 

                    
                    
                    var _hasLavaSec = Array.isArray(sectionAnimLayers) && sectionAnimLayers.some(function (l) { return l && l.effect === 'lava'; });
                    if (!_hasLavaSec) {
                        var _addLayerLocked = window.isProLocked && window.isProLocked();
                        html += '<button type="button" class="instinctor-btn impulse-add-section-anim-layer' + (_addLayerLocked ? ' impulse-pro-locked' : '') + '"' + (_addLayerLocked ? ' data-pro-locked="1" data-pro-label="Multiple animation layers"' : '') + ' style="width:100%;margin-top:12px">+ Add Layer</button>';
                    }
                    html += '</div>'; 

                    html += '</div>'; 
                    break;

                case 'grid':

                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-grid-fill-images" style="width:100%;margin-bottom:8px">Fill from Library</button>';

                    

                    
                    
                    var _gridImagesLightbox = !!(settings.images_lightbox && settings.images_lightbox != '0' && settings.images_lightbox !== false);
                    var _gridLiveWave       = !!(settings.live_wave && settings.live_wave != '0' && settings.live_wave !== false);
                    html += '<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px;font-size:11px;color:' + ImpC.text + '">'
                          +   '<label style="display:flex;align-items:center;gap:8px;cursor:pointer;white-space:nowrap" title="Open images in a lightbox">'
                          +     '<input type="checkbox" name="images_lightbox" value="1"' + (_gridImagesLightbox ? ' checked' : '') + '><span>Image lightbox</span>'
                          +   '</label>'
                          +   '<label style="display:flex;align-items:center;gap:8px;cursor:pointer;white-space:nowrap" title="Periodic flip-box peek + arrival teaser (flip-box grids, desktop)">'
                          +     '<span>Idle wave</span><input type="checkbox" name="live_wave" value="1"' + (_gridLiveWave ? ' checked' : '') + '>'
                          +   '</label>'
                          + '</div>';
                    html += '<div class="impulse-section-divider">Layout</div>';

                    html += '<label class="impulse-fit-parent-row" style="display:flex;align-items:center;justify-content:space-between;margin:0 0 8px;font-size:11px;color:' + ImpC.text + '" title="Stretch this container to fill its parent section height"><span>Fit parent height</span><input type="checkbox" class="impulse-fit-parent-cb" name="fill_container" value="1"' + (settings.fill_container ? ' checked' : '') + '></label>';

                    var gridLayoutMode = settings.layout_mode || (settings.auto_fit ? 'auto_fit' : 'grid');
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="layout_mode" style="display:flex;width:100%;gap:6px;margin-bottom:8px">';
                    [{v:'grid',l:'Grid'},{v:'masonry',l:'Masonry'},{v:'auto_fit',l:'Auto-fit'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (gridLayoutMode === o.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="layout_mode" value="' + gridLayoutMode + '">';
                    html += '<input type="hidden" name="auto_fit" value="' + (gridLayoutMode === 'auto_fit' ? '1' : '') + '">';
                    html += '</div>';
                    html += '<div class="impulse-auto-fit-off" style="display:' + (gridLayoutMode === 'auto_fit' ? 'none' : 'block') + '">';

                    

                    

                    

                    

                    
                    var _device  = window.impulseDevice || 'desktop';
                    var _csKey   = _device === 'desktop' ? 'cell_sizing' : 'cell_sizing_' + _device;
                    var _csVal   = settings[_csKey];
                    if (_csVal === undefined && _device !== 'desktop') _csVal = settings.cell_sizing; 
                    if (!_csVal) _csVal = 'stretch';

                    

                    
                    
                    html += '<div class="impulse-inline-right" data-responsive="true" style="margin-top:6px">';
                    html += '<label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Cell sizing</label>';
                    html += '<div class="impulse-btn-group" data-name="cell_sizing" style="display:flex;gap:3px">';
                    [{v:'stretch',l:'Stretch'},{v:'fit',l:'Fit'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (_csVal === o.v ? 'active' : '') + '" style="height:26px;padding:0 10px;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="cell_sizing" value="' + _csVal + '">';
                    html += '</div></div>';

                    

                    var _ghVal = settings.grid_halign || 'center';
                    html += '<div class="impulse-inline-right" style="margin-top:6px">';
                    html += '<label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Align</label>';
                    html += '<div class="impulse-btn-group" data-name="grid_halign" style="display:flex;gap:3px">';
                    [{v:'left',l:'Left'},{v:'center',l:'Center'},{v:'right',l:'Right'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (_ghVal === o.v ? 'active' : '') + '" style="height:26px;padding:0 10px;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="grid_halign" value="' + _ghVal + '">';
                    html += '</div></div>';

                    

                    

                    

                    

                    var _colsVal = String(getResponsiveValue(settings, 'columns', '2'));
                    html += '<div class="impulse-inline-right" data-responsive="true" style="margin-top:6px">';
                    html += '<label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Columns</label>';
                    html += '<div class="impulse-btn-group" data-name="columns" style="display:flex;gap:3px">';
                    ['1','2','3','4','5','6'].forEach(function (v) {
                        html += '<button type="button" data-value="' + v + '" class="' + (_colsVal === v ? 'active' : '') + '" style="width:26px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + v + '</button>';
                    });
                    html += '<input type="hidden" name="columns" value="' + _colsVal + '">';
                    html += '</div></div>';
                    
                    if (gridLayoutMode !== 'masonry') {

                        var _rowsVal = String(getResponsiveValue(settings, 'rows', '1'));
                        html += '<div class="impulse-inline-right" data-responsive="true" style="margin-top:6px">';
                        html += '<label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Rows</label>';
                        html += '<div class="impulse-btn-group" data-name="rows" style="display:flex;gap:3px">';
                        ['1','2','3','4','5','6'].forEach(function (v) {
                            html += '<button type="button" data-value="' + v + '" class="' + (_rowsVal === v ? 'active' : '') + '" style="width:26px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + v + '</button>';
                        });
                        html += '<input type="hidden" name="rows" value="' + _rowsVal + '">';
                        html += '</div></div>';
                    }

                    

                    

                    

                    

                    

                    html += '</div>';
                    html += '<div class="impulse-auto-fit-on" style="display:' + (gridLayoutMode === 'auto_fit' ? 'block' : 'none') + '">';
                    html += settingBtnGroup('direction', 'Direction', settings.direction || 'row', [
                        {v:'row',l:'Horizontal'},{v:'column',l:'Vertical'}
                    ]);
                    html += settingBtnGroup('justify', 'Justify', settings.justify || 'start', [
                        {v:'start',l:'Start'},{v:'center',l:'Center'},{v:'end',l:'End'},{v:'between',l:'Between'}
                    ]);
                    html += settingBtnGroup('align', 'Align', settings.align || 'stretch', [
                        {v:'stretch',l:'Stretch'},{v:'start',l:'Start'},{v:'center',l:'Center'},{v:'end',l:'End'}
                    ]);
                    html += settingBtnGroup('wrap', 'Wrap', settings.wrap || 'wrap', [
                        {v:'nowrap',l:'No Wrap'},{v:'wrap',l:'Wrap'}
                    ]);
                    html += '</div>';

                    if (window.impulseDevice === 'mobile') {
                        html += '<div class="impulse-section-divider">Layout</div>';
                        html += settingBtnGroupFull('mobile_layout', '', settings.mobile_layout || 'stack', [
                            {v:'stack',l:'Stack'},{v:'2col',l:'2 Columns'},{v:'keep',l:'Keep'}
                        ]);
                    }

                    

                    

                    

                    
                    if (gridLayoutMode === 'grid') {
                        var _colCount     = parseInt(_colsVal, 10) || 1;
                        var _rowCountSize = parseInt(_rowsVal || '1', 10) || 1;
                        html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                        for (var _csi = 0; _csi < _colCount; _csi++) {
                            html += settingSliderR(
                                'col_width_' + _csi,
                                'Col ' + (_csi + 1) + ' W',
                                settings, 10, 1, 30, 'fr'
                            );
                        }
                        for (var _rsi = 0; _rsi < _rowCountSize; _rsi++) {
                            html += settingSliderR(
                                'row_height_' + _rsi,
                                'Row ' + (_rsi + 1) + ' H',
                                settings, 0, 0, 1000, 'px'
                            );
                        }
                        html += '</div>';
                    }

                    

                    
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('gap_horizontal', 'Gap H',       settings, 20, 0, 300, 'px');
                    html += settingSliderR('gap_vertical',   'Gap V',       settings, 20, 0, 300, 'px');
                    html += settingSliderR('content_gap',    'Content Gap', settings, 0,  0, 100, 'px', false, 'Vertical spacing between blocks stacked inside each cell. Per-cell override available.');
                    html += settingSliderR('min_height',     'Min Height',  settings, 0,  0, 900, 'px');
                    html += settingWidthPreset(settings);
                    html += '</div>';

                    

                    

                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('cell_padding_h', 'Cell Pad H', settings, 0, 0, 200, 'px', false, 'Horizontal padding inside every cell. Selecting a single cell and setting its padding overrides this for that cell.');
                    html += settingSliderR('cell_padding_v', 'Cell Pad V', settings, 0, 0, 200, 'px', false, 'Vertical padding inside every cell. Selecting a single cell and setting its padding overrides this for that cell.');
                    html += settingSliderR('margin_top', 'Margin top', settings, 0, 0, 500, 'px');
                    html += settingSliderR('margin_bottom', 'Margin bottom', settings, 0, 0, 500, 'px');
                    html += settingSliderR('depth_intensity', 'Depth', settings, 0, 0, 100, '%', true, 'Per-cell 3D depth wave with mouse parallax + breathing motion. Hover a cell to fly it forward.');
                    html += settingSliderR('tilt_intensity', 'Cell tilt', settings, 0, 0, 100, '%', true, 'Per-cell 3D rotation toward the cursor. Independent of Depth — keeps content sharp/readable while cells follow the cursor.');
                    html += '</div>';

                    
                    
                    var _ctFrosted = !!(settings.frosted_glass && settings.frosted_glass !== '0');
                    html += '<div style="margin-top:8px"><label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="frosted_glass" value="1"' + (_ctFrosted ? ' checked' : '') + '> <span>Frosted glass</span></label></div>';

                    

                    

                    

                    
                    html += settingEntranceAnimation(settings);

                    

                    if (!settings.auto_fit && selectedGridCellIndex !== null && !isNaN(selectedGridCellIndex)) {
                        html += '<div class="impulse-grid-cell-bg-section">';
                        {
                            var cellIdx = selectedGridCellIndex;
                            var cellCols = parseInt(settings.columns) || 2;
                            var cellRow = Math.floor(cellIdx / cellCols) + 1;
                            var cellCol = (cellIdx % cellCols) + 1;

                            

                            

                            
                            var cbg  = settings['cell_bg_' + cellIdx] || '';
                            var cbgT = settings['cell_bg_gradient_to_' + cellIdx] || 'rgba(0,0,0,0)';
                            html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="justify-content:space-between;align-items:center;margin-top:0">'
                                 + '<span style="background:'+ImpC.surface2+';color:'+ImpC.white+';padding:2px 8px;border-radius:3px;font-size:11px">CELL R' + cellRow + ' C' + cellCol + '</span>'
                                 + '<span style="flex:1;height:1px;background:var(--imp-panel);margin:0 10px"></span>'
                                 + '<div style="display:flex;align-items:center;gap:3px">'
                                 +     settingColorSwatchOnly('cell_bg_' + cellIdx, cbg || 'transparent')
                                 +     settingColorSwatchOnly('cell_bg_gradient_to_' + cellIdx, cbgT)
                                 + '</div>'
                                 + '</div>';

                            

                            

                            

                            
                            var _device = window.impulseDevice || 'desktop';
                            var _hKey = _device === 'desktop' ? 'cell_halign_' + cellIdx : 'cell_halign_' + cellIdx + '_' + _device;
                            var _vKey = _device === 'desktop' ? 'cell_valign_' + cellIdx : 'cell_valign_' + cellIdx + '_' + _device;
                            var cellHVal = settings[_hKey] || settings['cell_halign_' + cellIdx] || 'center';
                            var cellVVal = settings[_vKey] || settings['cell_valign_' + cellIdx] || 'top';
                            
                            var arrowL = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';
                            var arrowR = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
                            var arrowU = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>';
                            var arrowD = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>';
                            var distV  = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 5h16"/><path d="M4 12h16"/><path d="M4 19h16"/></svg>';
                            var _alignBtn = function(val, cur, ic) {
                                return '<button type="button" data-value="' + val + '"' + (cur === val ? ' class="active"' : '') + ' style="flex:1">' + ic + '</button>';
                            };

                            

                            html += '<div class="impulse-margin-grid">';

                            html += settingSliderR('cell_rotate_' + cellIdx, 'Rotate', settings, 0, -45, 45, '°', true);
                            html += settingSliderR('cell_scale_' + cellIdx, 'Scale', settings, 100, 70, 130, '%', true);
                            
                            html += settingSliderR('cell_pad_h_' + cellIdx, 'Padding H', settings, 0, 0, 100, 'px', true);
                            html += settingSliderR('cell_pad_v_' + cellIdx, 'Padding V', settings, 0, 0, 100, 'px', true);

                            

                            
                            html += settingSliderR('cell_gap_' + cellIdx, 'Content Gap', settings, 0, 0, 100, 'px', true);

                            html += settingSliderR('cell_bg_gradient_angle_' + cellIdx, 'BG Angle', settings, 135, 0, 360, '°', true);
                            html += '</div>'; 

                            
                            
                            html += '<div class="impulse-setting-row impulse-cell-align-row" data-responsive="true" data-cell-idx="' + cellIdx + '" style="display:flex;gap:4px;margin-top:6px">';
                            html += '<div class="impulse-btn-group" data-name="cell_halign_' + cellIdx + '" data-toggleable="1" data-toggle-default="center" style="flex:1;display:flex">';
                            html += _alignBtn('left', cellHVal, arrowL);
                            html += _alignBtn('right', cellHVal, arrowR);
                            html += '<input type="hidden" name="cell_halign_' + cellIdx + '" value="' + cellHVal + '">';
                            html += '</div>';
                            html += '<div class="impulse-btn-group" data-name="cell_valign_' + cellIdx + '" data-toggleable="1" data-toggle-default="top" style="flex:1;display:flex">';
                            html += _alignBtn('top', cellVVal, arrowU);
                            html += _alignBtn('between', cellVVal, distV);
                            html += _alignBtn('bottom', cellVVal, arrowD);
                            html += '<input type="hidden" name="cell_valign_' + cellIdx + '" value="' + cellVVal + '">';
                            html += '</div>';
                            html += '</div>';

                            

                            

                            
                            var _cbW   = parseInt(settings['cell_border_width_' + cellIdx]) || 0;
                            var _cbC   = settings['cell_border_color_' + cellIdx] || '#e0e0e0';
                            var _cbgT  = settings['cell_border_gradient_to_' + cellIdx] || 'rgba(0,0,0,0)';

                            

                            
                            
                            html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="justify-content:space-between;align-items:center">'
                                 + '<span>Border</span>'
                                 + '<span style="flex:1;height:1px;background:var(--imp-panel);margin:0 10px"></span>'
                                 + '<div style="display:flex;align-items:center;gap:3px">'
                                 +     settingColorSwatchOnly('cell_border_color_' + cellIdx, _cbC)
                                 +     settingColorSwap('cell_border_color_' + cellIdx, 'cell_border_gradient_to_' + cellIdx, 'Swap border ↔ gradient')
                                 +     settingColorSwatchOnly('cell_border_gradient_to_' + cellIdx, _cbgT)
                                 + '</div>'
                                 + '</div>';
                            html += '<div class="impulse-cell-border-cell" data-cell-idx="' + cellIdx + '" style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px">';

                            
                            html += '<div style="display:flex;flex-direction:column;align-items:flex-start">';
                            html += '<label style="font-size:11px;color:#888;margin-bottom:6px">Thickness</label>';
                            html += '<div class="impulse-btn-group" style="display:flex;align-items:center;gap:3px">';

                            
                            
                            [1, 2, 3, 4].forEach(function(w) {
                                var on = (_cbW === w);
                                html += '<button type="button" class="impulse-cell-border-width-btn' + (on ? ' active' : '') + '" data-width="' + w + '" data-cell-idx="' + cellIdx + '" title="' + w + 'px border (click again to remove)" style="width:26px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + w + '</button>';
                            });
                            html += '<input type="hidden" name="cell_border_width_' + cellIdx + '" value="' + _cbW + '" data-responsive="true">';
                            html += '</div>';
                            html += '</div>';

                            

                            
                            var _tally = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"';
                            var _sideIcons = {
                                left:   _tally + '><path d="M4 4v16"/></svg>',
                                top:    _tally + ' style="transform:rotate(90deg)"><path d="M4 4v16"/></svg>',
                                right:  _tally + ' style="transform:rotate(180deg)"><path d="M4 4v16"/></svg>',
                                bottom: _tally + ' style="transform:rotate(270deg)"><path d="M4 4v16"/></svg>'
                            };
                            html += '<div style="display:flex;flex-direction:column;align-items:flex-start">';
                            html += '<label style="font-size:11px;color:#888;margin-bottom:6px">Edges</label>';
                            html += '<div class="impulse-border-sides impulse-cell-border-sides impulse-btn-group" data-cell-idx="' + cellIdx + '" style="display:flex;align-items:center;gap:3px">';
                            ['left','top','right','bottom'].forEach(function(side) {
                                var sv = settings['cell_border_' + side + '_' + cellIdx];
                                var stored = !(sv === '0' || sv === 0 || sv === false);
                                var liveActive = (_cbW > 0) && stored;
                                html += '<button type="button" class="impulse-border-side-btn' + (liveActive ? ' active' : '') + '" data-side="' + side + '" data-cell-idx="' + cellIdx + '" data-stored="' + (stored ? '1' : '0') + '" title="' + (side.charAt(0).toUpperCase() + side.slice(1)) + '" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box">' + _sideIcons[side] + '</button>';
                                html += '<input type="hidden" name="cell_border_' + side + '_' + cellIdx + '" value="' + (stored ? '1' : '0') + '">';
                            });
                            html += '</div>';
                            html += '</div>';
                            html += '</div>';

                            

                            
                            html += '<div class="impulse-cell-border-grad-wrap" data-cell-idx="' + cellIdx + '" style="margin-top:6px">';
                            html += '<div class="impulse-margin-grid">';

                            
                            html += settingSliderR('cell_border_gradient_angle_' + cellIdx, 'Border Angle', settings, 135, 0, 360, '°', true);
                            html += settingSliderR('cell_border_mouse_sens_' + cellIdx,    'Border Mouse', settings, 0,   0, 100, '%', true);

                            

                            
                            
                            html += settingSliderR('cell_border_spin_speed_' + cellIdx, 'Border Spin', settings, 0, 0, 90, '°/s', true);
                            html += settingSliderR('cell_radius_' + cellIdx, 'Radius', settings, 0, 0, 100, 'px', true);
                            html += '</div>';
                            html += '</div>';
                        }
                        html += '</div>';
                    }

                    

                    

                    
                    
                    break;

                case 'rows':

                    html += '<label class="impulse-fit-parent-row" style="display:flex;align-items:center;justify-content:space-between;margin:0 0 8px;font-size:11px;color:' + ImpC.text + '" title="Stretch this container to fill its parent section height"><span>Fit parent height</span><input type="checkbox" class="impulse-fit-parent-cb" name="fill_container" value="1"' + (settings.fill_container ? ' checked' : '') + '></label>';
                    
                    var chevronSvg = '<svg class="impulse-setting-section-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>';

                    var gridRows = settings.rows || [
                        { widths: [33.33, 33.33, 33.34], cells: [{}, {}, {}] },
                        { widths: [33.33, 33.33, 33.34], cells: [{}, {}, {}] }
                    ];
                    if (typeof gridRows === 'string') {
                        try { gridRows = JSON.parse(gridRows); } catch(e) { 
                            gridRows = [{ widths: [33.33, 33.33, 33.34], cells: [{}, {}, {}] }]; 
                        }
                    }

                    gridRows = gridRows.map(function(row) {
                        var widths = row.widths || [100];
                        var cells = row.cells || [{}];
                        while (cells.length < widths.length) cells.push({});
                        cells = cells.slice(0, widths.length);
                        return { widths: widths, cells: cells };
                    });

                    var cellsWithContent = {};
                    children.forEach(function(child) {
                        var key = child.cell_row + '-' + child.cell_col;
                        cellsWithContent[key] = true;
                    });

                    var selectedCellsForGrid = settings._selected_cells || [];
                    if (typeof selectedCellsForGrid === 'string') {
                        try { selectedCellsForGrid = JSON.parse(selectedCellsForGrid); } catch(e) { selectedCellsForGrid = []; }
                    }
                    var selectedCellsMap = {};
                    selectedCellsForGrid.forEach(function(c) { selectedCellsMap[c] = true; });

                    

                    
                    html += '<div class="impulse-cg-editor" style="width:100%;display:flex;flex-direction:column;gap:4px">';
                    gridRows.forEach(function(row, rowIdx) {
                        html += '<div class="impulse-cg-row" data-row="' + rowIdx + '" style="display:flex;flex-direction:column;align-items:stretch;position:relative">';

                        var widths = row.widths || [100];
                        var cells = row.cells || [{}];

                        

                        html += '<div class="impulse-cg-row-body" style="display:flex;align-items:stretch;min-height:28px">';
                        html += '<div class="impulse-cg-row-cells" style="display:flex;flex:1;min-width:0;gap:2px">';

                        widths.forEach(function(w, colIdx) {
                            var cellKey = rowIdx + '-' + colIdx;
                            var hasContent = cellsWithContent[cellKey];
                            var isSelected = selectedCellsMap[cellKey];
                            var classes = 'impulse-cg-cell';
                            if (hasContent) classes += ' has-content';
                            if (isSelected) classes += ' selected';
                            
                            var inlineBg = (!isSelected && !hasContent) ? ('background:' + ImpC.border + ';') : '';
                            html += '<div class="' + classes + '" data-row="' + rowIdx + '" data-col="' + colIdx + '" style="flex:' + w + ';min-height:28px;' + inlineBg + 'border-radius:3px;cursor:pointer;position:relative;display:flex;align-items:center;justify-content:center"' + (hasContent ? ' draggable="true"' : '') + '>';
                            html += '<span class="cg-cell-pct" data-row="' + rowIdx + '" data-col="' + colIdx + '" contenteditable="true" spellcheck="false">' + Math.round(w) + '</span>';
                            if (widths.length > 1) {
                                html += '<button type="button" class="cg-cell-remove" data-row="' + rowIdx + '" data-col="' + colIdx + '" title="Remove cell"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>';
                            }
                            html += '</div>';
                        });

                        html += '</div>';

                        var plusSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>';
                        html += '<div class="impulse-cg-add-cell" data-row="' + rowIdx + '" title="Add cell" style="width:22px;flex-shrink:0;border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.dim+';margin-left:4px">' + plusSvg + '</div>';

                        
                        if (gridRows.length > 1) {
                            var _gripSvg = '<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><circle cx="9" cy="5" r="1.5"/><circle cx="15" cy="5" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/></svg>';
                            html += '<div class="impulse-cg-row-drag" data-row="' + rowIdx + '" title="Drag to reorder" style="width:22px;flex-shrink:0;border:1px solid '+ImpC.border+';border-radius:3px;cursor:grab;display:flex;align-items:center;justify-content:center;color:'+ImpC.dim+';margin-left:4px">' + _gripSvg + '</div>';
                        }

                        
                        if (gridRows.length > 1) {

                            var xSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
                            html += '<div class="impulse-cg-remove-row" data-row="' + rowIdx + '" title="Remove row" style="width:22px;flex-shrink:0;border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.dim+';margin-left:4px">' + xSvg + '</div>';
                        }
                        html += '</div>'; 
                        html += '</div>'; 
                    });
                    html += '<div class="impulse-cg-add-row" title="Add row" style="height:20px;border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.dim+';margin-top:2px"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg></div>';
                    html += '</div>';
                    
                    html += '<input type="hidden" name="rows" value=\'' + JSON.stringify(gridRows).replace(/'/g, '&#39;') + '\'>';

                    

                    html += '<div class="impulse-margin-grid" style="margin-top:16px">';
                    html += settingSliderR('row_gap',     'Row Gap',     settings, 16, 0, 60,  'px');
                    html += settingSliderR('cell_gap',    'Cell Gap',    settings, 16, 0, 60,  'px');
                    html += settingSliderR('content_gap', 'Content Gap', settings, 0,  0, 100, 'px', false, 'Vertical spacing between blocks stacked inside each cell');
                    html += settingSliderR('cell_radius', 'Cell Radius', settings, 0,  0, 30,  'px');
                    html += settingSliderR('min_height',  'Min Height',  settings, 0,  0, 900, 'px');
                    html += settingWidthPreset(settings);
                    html += '</div>';

                    var selectedCells = settings._selected_cells || [];
                    if (typeof selectedCells === 'string') {
                        try { selectedCells = JSON.parse(selectedCells); } catch(e) { selectedCells = []; }
                    }

                    if (selectedCells.length > 1) {
                        
                        var allSameRow = true;
                        var firstRow = selectedCells[0] ? selectedCells[0].split('-')[0] : null;
                        selectedCells.forEach(function(c) {
                            if (c.split('-')[0] !== firstRow) allSameRow = false;
                        });
                        
                        html += '<div class="impulse-setting-section" style="margin-top:12px">';
                        html += '<div class="impulse-setting-section-header">' + chevronSvg + '<span class="impulse-setting-section-title">' + selectedCells.length + ' Cells Selected</span></div>';
                        html += '<div class="impulse-setting-section-content">';
                        if (allSameRow) {
                            html += '<button type="button" class="instinctor-btn impulse-rows-merge" style="width:100%;background:'+ImpC.surface2+';color:'+ImpC.white+'">Merge Cells</button>';
                        } else {
                            html += '<div style="padding:8px;background:'+ImpC.panel+';border-radius:4px;font-size:12px;color:#888;text-align:center">Select cells in the same row to merge</div>';
                        }
                        html += '</div></div>';
                    } else if (selectedCells.length === 1) {
                        
                        var cellKey = selectedCells[0];
                        var parts = cellKey.split('-');
                        var selRow = parseInt(parts[0]);
                        var selCol = parseInt(parts[1]);
                        
                        if (!isNaN(selRow) && !isNaN(selCol) && gridRows[selRow] && gridRows[selRow].cells[selCol]) {
                            var cellData = gridRows[selRow].cells[selCol] || {};
                            var hasCellImage = cellData.bg_image ? true : false;
                            
                            html += '<div class="impulse-setting-section impulse-cell-settings-section" style="margin-top:12px">';
                            html += '<div class="impulse-setting-section-header">';
                            html += chevronSvg;
                            html += '<span class="impulse-setting-section-title" style="display:flex;align-items:center;gap:8px">';
                            html += '<span style="background:'+ImpC.surface2+';color:'+ImpC.white+';padding:2px 8px;border-radius:3px;font-size:11px">R' + (selRow + 1) + ' C' + (selCol + 1) + '</span>';
                            html += 'Cell Settings';
                            html += '</span></div>';
                            html += '<div class="impulse-setting-section-content">';

                            var arrowL = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';
                            var arrowR = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
                            var arrowU = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>';
                            var arrowD = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>';
                            var distV  = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 5h16"/><path d="M4 12h16"/><path d="M4 19h16"/></svg>';
                            var currentHalign = getCellDeviceVal(cellData, 'halign', 'center');
                            var currentValign = getCellDeviceVal(cellData, 'valign', 'top');
                            html += '<div class="impulse-setting-row" style="display:flex;gap:4px">';
                            html += '<div class="impulse-btn-group" data-name="cell_halign" data-toggleable="1" data-toggle-default="center" style="flex:1;display:flex">';
                            html += '<button type="button" data-value="left"' + (currentHalign === 'left' ? ' class="active"' : '') + ' style="flex:1">' + arrowL + '</button>';
                            html += '<button type="button" data-value="right"' + (currentHalign === 'right' ? ' class="active"' : '') + ' style="flex:1">' + arrowR + '</button>';
                            html += '<input type="hidden" name="cell_halign" value="' + currentHalign + '">';
                            html += '</div>';
                            html += '<div class="impulse-btn-group" data-name="cell_valign" data-toggleable="1" data-toggle-default="top" style="flex:1;display:flex">';
                            html += '<button type="button" data-value="top"' + (currentValign === 'top' ? ' class="active"' : '') + ' style="flex:1">' + arrowU + '</button>';
                            html += '<button type="button" data-value="between"' + (currentValign === 'between' ? ' class="active"' : '') + ' style="flex:1">' + distV + '</button>';
                            html += '<button type="button" data-value="bottom"' + (currentValign === 'bottom' ? ' class="active"' : '') + ' style="flex:1">' + arrowD + '</button>';
                            html += '<input type="hidden" name="cell_valign" value="' + currentValign + '">';
                            html += '</div>';
                            html += '</div>';

                            html += '<div style="display:flex;gap:12px;align-items:center;height:26px">';
                            
                            html += '<div class="impulse-cell-bg-color-row" style="' + (hasCellImage ? 'display:none' : 'display:flex;align-items:center;gap:6px') + '">';
                            html += settingColorSwatchOnly('cell_bg_color', cellData.bg_color || 'transparent');
                            html += '<span style="font-size:11px;color:#888">Background</span>';
                            html += '</div>';
                            
                            html += '<div class="impulse-cell-select-image-row" style="' + (hasCellImage ? 'display:none' : 'display:block;margin-left:auto') + '">';
                            html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="cell_bg_image" style="height:26px">Select Image</button>';
                            html += '</div>';
                            html += '<input type="hidden" name="cell_bg_image" value="' + (cellData.bg_image || '') + '">';
                            html += '</div>';

                            html += '<div class="impulse-cell-image-options" style="' + (hasCellImage ? '' : 'display:none') + '">';
                            
                            if (cellData.bg_image) {
                                html += '<div class="impulse-image-preview" style="margin-top:8px">';
                                html += '<img src="' + cellData.bg_image + '" style="max-width:100%;max-height:60px;border-radius:4px">';
                                html += '<button type="button" class="impulse-remove-image-btn" data-name="cell_bg_image" style="display:block;margin-top:4px;font-size:11px;color:#888;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';padding:4px 8px;border-radius:3px;cursor:pointer">Remove</button>';
                                html += '</div>';
                            }
                            
                            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="cell_bg_fit" style="display:flex;width:100%;gap:3px;margin-top:8px">';
                            var fitOptions = [{v:'cover',l:'Cover'},{v:'contain',l:'Contain'},{v:'auto',l:'Original'}];
                            var currentFit = cellData.bg_fit || 'cover';
                            fitOptions.forEach(function(opt) {
                                html += '<button type="button" class="' + (opt.v === currentFit ? 'active' : '') + '" data-value="' + opt.v + '" style="flex:1;height:26px;font-size:11px">' + opt.l + '</button>';
                            });
                            html += '<input type="hidden" name="cell_bg_fit" value="' + currentFit + '">';
                            html += '</div>';
                            
                            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="cell_bg_position" style="display:flex;width:100%;gap:3px;margin-top:3px">';
                            var posOptions = [{v:'top',l:'Top'},{v:'center',l:'Center'},{v:'bottom',l:'Bottom'}];
                            var currentPos = cellData.bg_position || 'center';
                            posOptions.forEach(function(opt) {
                                html += '<button type="button" class="' + (opt.v === currentPos ? 'active' : '') + '" data-value="' + opt.v + '" style="flex:1;height:26px;font-size:11px">' + opt.l + '</button>';
                            });
                            html += '<input type="hidden" name="cell_bg_position" value="' + currentPos + '">';
                            html += '</div>';
                            html += '</div>';

                            html += '<div class="impulse-inline-right" style="margin-top:12px">';
                            html += '<label style="font-size:11px;color:#888">Link URL</label>';
                            html += '<input type="text" name="cell_url" value="' + escapeHtml(cellData.url || '') + '" placeholder="https://" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                            html += '</div>';

                            var currentRowHeight = gridRows[selRow].row_height !== undefined ? gridRows[selRow].row_height : (settings.row_height || 120);
                            html += '<div class="impulse-section-divider">Padding</div>';
                            html += '<div class="impulse-margin-grid">';
                            
                            var cellPaddingSides = getCellDeviceVal(cellData, 'padding_sides', cellData.padding_left || 0);
                            html += settingSlider('cell_padding_sides', 'Sides', cellPaddingSides, 0, 60, 'px');
                            html += settingSlider('cell_padding_top', 'Top', getCellDeviceVal(cellData, 'padding_top', 0), 0, 60, 'px');
                            html += settingSlider('cell_padding_bottom', 'Bottom', getCellDeviceVal(cellData, 'padding_bottom', 0), 0, 60, 'px');

                            
                            var _rhHtml = settingSlider('_row_height', 'Row Height', currentRowHeight, 60, 400, 'px');
                            _rhHtml = _rhHtml.replace('<input type="range"', '<input type="range" data-row="' + selRow + '"');
                            html += _rhHtml;
                            html += '</div>';

                            
                            var cellBorderWidth = cellData.border_width || 0;
                            var cellBorderColor = cellData.border_color || ''+ImpC.text+'';
                            html += '<div class="impulse-section-divider impulse-divider-with-toggle">Border'
                                + '<span style="flex:1;height:1px;background:var(--imp-panel)"></span>'
                                + settingColorSwatchOnly('cell_border_color', cellBorderColor)
                                + '</div>';
                            html += settingSlider('cell_border_width', 'Width', cellBorderWidth, 0, 10, 'px');
                            
                            function isCellBorderEnabled(val) {
                                if (val === undefined || val === null) return true;
                                if (val === false || val === '0' || val === 0) return false;
                                return true;
                            }
                            html += '<div class="impulse-border-sides" data-prefix="cell_" style="display:' + (parseInt(cellBorderWidth) > 0 ? 'flex' : 'none') + ';align-items:center;gap:3px;margin-top:8px">';
                            var cellSides = ['left', 'top', 'right', 'bottom'];

                            var _tallyCG = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"';
                            var _cgEdgeIcon = {
                                left:   _tallyCG + '><path d="M4 4v16"/></svg>',
                                top:    _tallyCG + ' style="transform:rotate(90deg)"><path d="M4 4v16"/></svg>',
                                right:  _tallyCG + ' style="transform:rotate(180deg)"><path d="M4 4v16"/></svg>',
                                bottom: _tallyCG + ' style="transform:rotate(270deg)"><path d="M4 4v16"/></svg>'
                            };
                            for (var si = 0; si < 4; si++) {
                                var cSide = cellSides[si];
                                var cChecked = isCellBorderEnabled(cellData['border_' + cSide]);
                                html += '<button type="button" class="impulse-border-side-btn' + (cChecked ? ' active' : '') + '" data-side="' + cSide + '" title="' + cSide.charAt(0).toUpperCase() + cSide.slice(1) + '" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box">' + _cgEdgeIcon[cSide] + '</button>';
                                html += '<input type="hidden" name="cell_border_' + cSide + '" value="' + (cChecked ? '1' : '0') + '">';
                            }
                            html += '</div>';

                            html += '</div></div>';
                        }
                    } else {
                        html += '<div class="impulse-cell-select-hint" style="margin-top:12px;padding:12px;background:'+ImpC.panel+';border-radius:6px;text-align:center;color:#888;font-size:12px">';
                        html += 'Click cell to style it<br>Shift+click to multi-select<br>Drag borders to resize';
                        html += '</div>';
                    }
                    html += '<input type="hidden" name="_selected_cells" value=\'' + JSON.stringify(selectedCells) + '\'>';

                    
                    var _ctFrosted = !!(settings.frosted_glass && settings.frosted_glass !== '0');
                    html += '<div style="margin-top:10px"><label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="frosted_glass" value="1"' + (_ctFrosted ? ' checked' : '') + '> <span>Frosted glass</span></label></div>';

                    
                    
                    html += '<div class="impulse-setting-section collapsed" style="margin-top:12px">';
                    html += '<div class="impulse-setting-section-header impulse-divider-with-toggle" style="display:flex;align-items:center;gap:8px">'
                        + chevronSvg
                        + '<span class="impulse-setting-section-title">Container</span>'
                        + '</div>';

                    html += '<div class="impulse-setting-section-content">';
                    
                    html += '<div class="impulse-section-divider">Box</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('padding_sides', 'Padding Sides', settings, 0, 0, 60, 'px');
                    html += settingSliderR('padding_top', 'Padding Top', settings, 0, 0, 60, 'px');
                    html += settingSliderR('padding_bottom', 'Padding Bottom', settings, 0, 0, 60, 'px');
                    html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 30, 'px');
                    html += settingSliderR('margin_top', 'Margin Top', settings, 0, 0, 500, 'px');
                    html += settingSliderR('margin_bottom', 'Margin Bottom', settings, 0, 0, 500, 'px');
                    html += settingSliderR('depth_intensity', 'Depth', settings, 0, 0, 100, '%', true, 'Per-cell 3D depth wave with mouse parallax + breathing motion. Hover a cell to fly it forward.');
                    html += settingSliderR('tilt_intensity', 'Cell tilt', settings, 0, 0, 100, '%', true, 'Per-cell 3D rotation toward the cursor. Independent of Depth — keeps content sharp/readable while cells follow the cursor.');
                    html += '</div>';

                    html += settingBorder('container_', settings, 'Container Border');
                    html += '</div></div>';

                    if (window.impulseDevice === 'mobile') {
                        html += '<div class="impulse-section-divider">Layout</div>';
                        html += settingBtnGroupFull('mobile_layout', '', settings.mobile_layout || 'stack', [
                            {v:'stack',l:'Stack'},{v:'2col',l:'2 Columns'},{v:'keep',l:'Keep'}
                        ]);
                    }

                    html += settingEntranceAnimation(settings);

                    
                    break;

                case 'columns':

                    html += '<label class="impulse-fit-parent-row" style="display:flex;align-items:center;justify-content:space-between;margin:0 0 8px;font-size:11px;color:' + ImpC.text + '" title="Stretch this container to fill its parent section height"><span>Fit parent height</span><input type="checkbox" class="impulse-fit-parent-cb" name="fill_container" value="1"' + (settings.fill_container ? ' checked' : '') + '></label>';

                    
                    var chevronSvg = '<svg class="impulse-setting-section-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>';

                    var gridCols = settings.columns || [
                        { width: 33.33, cells: [{}] },
                        { width: 33.33, cells: [{}, {}] },
                        { width: 33.34, cells: [{}, {}, {}] }
                    ];
                    if (typeof gridCols === 'string') {
                        try { gridCols = JSON.parse(gridCols); } catch(e) {
                            gridCols = [{ width: 33.33, cells: [{}] }, { width: 33.33, cells: [{}, {}] }, { width: 33.34, cells: [{}, {}, {}] }];
                        }
                    }

                    gridCols = gridCols.map(function(col) {
                        var width = col.width || (100 / gridCols.length);
                        var cells = col.cells || [{}];
                        if (cells.length === 0) cells = [{}];
                        return { width: width, cells: cells };
                    });

                    var cellsWithContent = {};
                    children.forEach(function(child) {
                        var key = child.cell_col + '-' + child.cell_row;
                        cellsWithContent[key] = true;
                    });

                    var selectedCellsForGrid = settings._selected_cells || [];
                    if (typeof selectedCellsForGrid === 'string') {
                        try { selectedCellsForGrid = JSON.parse(selectedCellsForGrid); } catch(e) { selectedCellsForGrid = []; }
                    }
                    var selectedCellsMap = {};
                    selectedCellsForGrid.forEach(function(c) { selectedCellsMap[c] = true; });

                    

                    
                    
                    html += '<div class="impulse-lg-editor" style="width:100%">';

                    

                    
                    html += '<div class="impulse-lg-pcts" data-grid-pcts="1" style="padding-right:24px">';
                    gridCols.forEach(function(col, colIdx) {
                        var colW = col.width || (100 / gridCols.length);
                        html += '<span class="lg-col-pct" data-col="' + colIdx + '" style="flex:' + colW + ';min-width:20px" contenteditable="true" spellcheck="false">' + Math.round(colW) + '</span>';
                    });
                    html += '</div>';

                    html += '<div class="impulse-lg-editor-cols" style="display:flex;width:100%;min-height:120px;position:relative;gap:2px">';

                    gridCols.forEach(function(col, colIdx) {
                        var colWidth = col.width || (100 / gridCols.length);
                        html += '<div class="impulse-lg-col" data-col="' + colIdx + '" style="flex:' + colWidth + ';display:flex;flex-direction:column;gap:4px;min-width:0;position:relative">';
                        if (gridCols.length > 1) {
                            html += '<div class="impulse-lg-col-header" style="display:flex;justify-content:flex-end;align-items:center;padding:2px 4px;min-height:14px">';
                            html += '<button type="button" class="impulse-lg-col-remove" data-col="' + colIdx + '" title="Remove column"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>';
                            html += '</div>';
                        }

                        var cells = col.cells || [{}];
                        cells.forEach(function(cellData, rowIdx) {
                            var cellKey = colIdx + '-' + rowIdx;
                            var hasContent = cellsWithContent[cellKey];
                            var isSelected = selectedCellsMap[cellKey];
                            var classes = 'impulse-lg-cell';
                            if (hasContent) classes += ' has-content';
                            if (isSelected) classes += ' selected';

                            var lgInlineBg = (!isSelected && !hasContent) ? ('background:' + ImpC.border + ';') : '';
                            html += '<div class="' + classes + '" data-col="' + colIdx + '" data-row="' + rowIdx + '" style="flex:1;min-height:28px;' + lgInlineBg + 'border-radius:3px;cursor:pointer;position:relative;display:flex;align-items:center;justify-content:center"' + (hasContent ? ' draggable="true"' : '') + '>';
                            if (cells.length > 1) {
                                html += '<button type="button" class="lg-cell-remove" data-col="' + colIdx + '" data-row="' + rowIdx + '" title="Remove cell"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>';
                            }
                            html += '</div>';
                        });

                        var lgPlusSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>';
                        html += '<div class="impulse-lg-add-cell" data-col="' + colIdx + '" style="min-height:20px;border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.dim+'">' + lgPlusSvg + '</div>';
                        html += '</div>';
                    });

                    html += '<div class="impulse-lg-add-col" style="width:22px;flex-shrink:0;border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.dim+'"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg></div>';
                    html += '</div></div>';
                    
                    html += '<input type="hidden" name="columns" value=\'' + JSON.stringify(gridCols).replace(/'/g, '&#39;') + '\'>';

                    
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:16px">';
                    html += settingSliderR('col_gap',     'Column Gap',  settings, 16,  0, 60,  'px');
                    html += settingSliderR('cell_gap',    'Cell Gap',    settings, 16,  0, 60,  'px');
                    html += settingSliderR('content_gap', 'Content Gap', settings, 0,   0, 100, 'px', false, 'Vertical spacing between blocks stacked inside each cell');
                    html += settingSliderR('min_height',  'Min Height',  settings, 200, 0, 600, 'px');
                    html += settingSliderR('cell_radius', 'Cell Radius', settings, 0,   0, 30,  'px');
                    html += settingWidthPreset(settings);
                    html += '</div>';

                    var selectedCells = settings._selected_cells || [];
                    if (typeof selectedCells === 'string') {
                        try { selectedCells = JSON.parse(selectedCells); } catch(e) { selectedCells = []; }
                    }

                    if (selectedCells.length === 1) {
                        var cellKey = selectedCells[0];
                        var parts = cellKey.split('-');
                        var selCol = parseInt(parts[0]);
                        var selRow = parseInt(parts[1]);
                        
                        if (!isNaN(selCol) && !isNaN(selRow) && gridCols[selCol] && gridCols[selCol].cells[selRow]) {
                            var cellData = gridCols[selCol].cells[selRow] || {};
                            var hasCellImage = cellData.bg_image ? true : false;
                            
                            html += '<div class="impulse-setting-section impulse-cell-settings-section" style="margin-top:12px">';
                            html += '<div class="impulse-setting-section-header">';
                            html += chevronSvg;
                            html += '<span class="impulse-setting-section-title" style="display:flex;align-items:center;gap:8px">';
                            html += '<span style="background:'+ImpC.surface2+';color:'+ImpC.white+';padding:2px 8px;border-radius:3px;font-size:11px">C' + (selCol + 1) + ' R' + (selRow + 1) + '</span>';
                            html += 'Cell Settings';
                            html += '</span></div>';
                            html += '<div class="impulse-setting-section-content">';

                            html += '<div class="impulse-section-divider">Content Align</div>';
                            var arrowL = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';
                            var arrowR = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
                            var arrowU = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>';
                            var arrowD = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>';
                            var distV  = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 5h16"/><path d="M4 12h16"/><path d="M4 19h16"/></svg>';
                            var currentHalign = getCellDeviceVal(cellData, 'halign', 'center');
                            var currentValign = getCellDeviceVal(cellData, 'valign', 'top');
                            html += '<div class="impulse-setting-row" style="display:flex;gap:4px">';
                            html += '<div class="impulse-btn-group" data-name="cell_halign" data-toggleable="1" data-toggle-default="center" style="flex:1;display:flex">';
                            html += '<button type="button" data-value="left"' + (currentHalign === 'left' ? ' class="active"' : '') + ' style="flex:1">' + arrowL + '</button>';
                            html += '<button type="button" data-value="right"' + (currentHalign === 'right' ? ' class="active"' : '') + ' style="flex:1">' + arrowR + '</button>';
                            html += '<input type="hidden" name="cell_halign" value="' + currentHalign + '">';
                            html += '</div>';
                            html += '<div class="impulse-btn-group" data-name="cell_valign" data-toggleable="1" data-toggle-default="top" style="flex:1;display:flex">';
                            html += '<button type="button" data-value="top"' + (currentValign === 'top' ? ' class="active"' : '') + ' style="flex:1">' + arrowU + '</button>';
                            html += '<button type="button" data-value="between"' + (currentValign === 'between' ? ' class="active"' : '') + ' style="flex:1">' + distV + '</button>';
                            html += '<button type="button" data-value="bottom"' + (currentValign === 'bottom' ? ' class="active"' : '') + ' style="flex:1">' + arrowD + '</button>';
                            html += '<input type="hidden" name="cell_valign" value="' + currentValign + '">';
                            html += '</div>';
                            html += '</div>';

                            html += '<div style="display:flex;gap:12px;align-items:center;height:26px">';
                            html += '<div class="impulse-cell-bg-color-row" style="' + (hasCellImage ? 'display:none' : 'display:flex;align-items:center;gap:6px') + '">';
                            html += settingColorSwatchOnly('cell_bg_color', cellData.bg_color || 'transparent');
                            html += '<span style="font-size:11px;color:#888">Background</span>';
                            html += '</div>';
                            html += '<div class="impulse-cell-select-image-row" style="' + (hasCellImage ? 'display:none' : 'display:block;margin-left:auto') + '">';
                            html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="cell_bg_image" style="height:26px">Select Image</button>';
                            html += '</div>';
                            html += '<input type="hidden" name="cell_bg_image" value="' + (cellData.bg_image || '') + '">';
                            html += '</div>';

                            html += '<div class="impulse-cell-image-options" style="' + (hasCellImage ? '' : 'display:none') + '">';
                            if (cellData.bg_image) {
                                html += '<div class="impulse-image-preview" style="margin-top:8px">';
                                html += '<img src="' + cellData.bg_image + '" style="max-width:100%;max-height:60px;border-radius:4px">';
                                html += '<button type="button" class="impulse-remove-image-btn" data-name="cell_bg_image" style="display:block;margin-top:4px;font-size:11px;color:#888;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';padding:4px 8px;border-radius:3px;cursor:pointer">Remove</button>';
                                html += '</div>';
                            }
                            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="cell_bg_fit" style="display:flex;width:100%;gap:3px;margin-top:8px">';
                            var fitOptions = [{v:'cover',l:'Cover'},{v:'contain',l:'Contain'},{v:'auto',l:'Original'}];
                            var currentFit = cellData.bg_fit || 'cover';
                            fitOptions.forEach(function(opt) {
                                html += '<button type="button" class="' + (opt.v === currentFit ? 'active' : '') + '" data-value="' + opt.v + '" style="flex:1;height:26px;font-size:11px">' + opt.l + '</button>';
                            });
                            html += '<input type="hidden" name="cell_bg_fit" value="' + currentFit + '">';
                            html += '</div>';
                            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="cell_bg_position" style="display:flex;width:100%;gap:3px;margin-top:3px">';
                            var posOptions = [{v:'top',l:'Top'},{v:'center',l:'Center'},{v:'bottom',l:'Bottom'}];
                            var currentPos = cellData.bg_position || 'center';
                            posOptions.forEach(function(opt) {
                                html += '<button type="button" class="' + (opt.v === currentPos ? 'active' : '') + '" data-value="' + opt.v + '" style="flex:1;height:26px;font-size:11px">' + opt.l + '</button>';
                            });
                            html += '<input type="hidden" name="cell_bg_position" value="' + currentPos + '">';
                            html += '</div>';
                            html += '</div>';

                            html += '<div class="impulse-inline-right" style="margin-top:12px">';
                            html += '<label style="font-size:11px;color:#888">Link URL</label>';
                            html += '<input type="text" name="cell_url" value="' + escapeHtml(cellData.url || '') + '" placeholder="https://" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                            html += '</div>';

                            html += '<div class="impulse-section-divider">Padding</div>';
                            html += '<div class="impulse-margin-grid">';
                            var cellPaddingSides = getCellDeviceVal(cellData, 'padding_sides', 0);
                            html += settingSlider('cell_padding_sides', 'Sides', cellPaddingSides, 0, 60, 'px');
                            html += settingSlider('cell_padding_top', 'Top', getCellDeviceVal(cellData, 'padding_top', 0), 0, 60, 'px');
                            html += settingSlider('cell_padding_bottom', 'Bottom', getCellDeviceVal(cellData, 'padding_bottom', 0), 0, 60, 'px');
                            html += '</div>';

                            html += '<div class="impulse-section-divider">Border</div>';
                            var cellBorderWidth = cellData.border_width || 0;
                            var cellBorderColor = cellData.border_color || ''+ImpC.text+'';
                            html += '<div class="impulse-margin-grid">';
                            html += settingSlider('cell_border_width', 'Width', cellBorderWidth, 0, 10, 'px');
                            html += '<div class="impulse-setting-row" style="margin-bottom:0"><label style="font-size:11px;color:#888;margin-bottom:6px">Color</label>' + settingColorSwatchOnly('cell_border_color', cellBorderColor) + '</div>';
                            html += '</div>';
                            function isLGCellBorderEnabled(val) {
                                if (val === undefined || val === null) return true;
                                if (val === false || val === '0' || val === 0) return false;
                                return true;
                            }
                            html += '<div class="impulse-border-sides" data-prefix="cell_" style="display:' + (parseInt(cellBorderWidth) > 0 ? 'flex' : 'none') + ';align-items:center;gap:3px;margin-top:8px">';
                            var cellSides = ['left', 'top', 'right', 'bottom'];

                            var _tallyFF = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"';
                            var _ffEdgeIcon = {
                                left:   _tallyFF + '><path d="M4 4v16"/></svg>',
                                top:    _tallyFF + ' style="transform:rotate(90deg)"><path d="M4 4v16"/></svg>',
                                right:  _tallyFF + ' style="transform:rotate(180deg)"><path d="M4 4v16"/></svg>',
                                bottom: _tallyFF + ' style="transform:rotate(270deg)"><path d="M4 4v16"/></svg>'
                            };
                            for (var si = 0; si < 4; si++) {
                                var cSide = cellSides[si];
                                var cChecked = isLGCellBorderEnabled(cellData['border_' + cSide]);
                                html += '<button type="button" class="impulse-border-side-btn' + (cChecked ? ' active' : '') + '" data-side="' + cSide + '" title="' + cSide.charAt(0).toUpperCase() + cSide.slice(1) + '" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box">' + _ffEdgeIcon[cSide] + '</button>';
                                html += '<input type="hidden" name="cell_border_' + cSide + '" value="' + (cChecked ? '1' : '0') + '">';
                            }
                            html += '</div>';

                            html += '</div></div>';
                        }
                    } else {
                        html += '<div class="impulse-cell-select-hint" style="margin-top:12px;padding:12px;background:'+ImpC.panel+';border-radius:6px;text-align:center;color:#888;font-size:12px">';
                        html += 'Click cell to style it<br>Shift+click to multi-select<br>Drag borders to resize';
                        html += '</div>';
                    }
                    html += '<input type="hidden" name="_selected_cells" value=\'' + JSON.stringify(selectedCells) + '\'>';

                    
                    var _ctFrosted = !!(settings.frosted_glass && settings.frosted_glass !== '0');
                    html += '<div style="margin-top:10px"><label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="frosted_glass" value="1"' + (_ctFrosted ? ' checked' : '') + '> <span>Frosted glass</span></label></div>';

                    html += '<div class="impulse-setting-section collapsed" style="margin-top:12px">';
                    html += '<div class="impulse-setting-section-header">' + chevronSvg + '<span class="impulse-setting-section-title">Container</span></div>';
                    html += '<div class="impulse-setting-section-content">';

                    html += '<div class="impulse-section-divider">Box</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('padding_sides', 'Padding Sides', settings, 0, 0, 60, 'px');
                    html += settingSliderR('padding_top', 'Padding Top', settings, 0, 0, 60, 'px');
                    html += settingSliderR('padding_bottom', 'Padding Bottom', settings, 0, 0, 60, 'px');
                    html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 30, 'px');
                    html += settingSliderR('margin_top', 'Margin Top', settings, 0, 0, 500, 'px');
                    html += settingSliderR('margin_bottom', 'Margin Bottom', settings, 0, 0, 500, 'px');
                    html += settingSliderR('depth_intensity', 'Depth', settings, 0, 0, 100, '%', true, 'Per-cell 3D depth wave with mouse parallax + breathing motion. Hover a cell to fly it forward.');
                    html += settingSliderR('tilt_intensity', 'Cell tilt', settings, 0, 0, 100, '%', true, 'Per-cell 3D rotation toward the cursor. Independent of Depth — keeps content sharp/readable while cells follow the cursor.');
                    html += '</div>';

                    html += settingBorder('container_', settings, 'Container Border');
                    html += '</div></div>';

                    if (window.impulseDevice === 'mobile') {
                        html += '<div class="impulse-section-divider">Layout</div>';
                        html += settingBtnGroupFull('mobile_layout', '', settings.mobile_layout || 'stack', [
                            {v:'stack',l:'Stack'},{v:'2col',l:'2 Columns'},{v:'keep',l:'Keep'}
                        ]);
                    }

                    html += settingEntranceAnimation(settings);
                    
                    break;

                case 'text':
                    
                    html += settingRichText('content', 'Content', getResponsiveValue(settings, 'content', '') || '', {
                        rows: 6,
                        placeholder: 'Add your text here...'
                    });
                    
                    html += '<div style="display:flex;gap:16px;margin-top:3px">';
                    html += '<div style="flex:1">';
                    html += '<label style="font-size:11px;color:#888;margin-bottom:4px;display:block">Alignment</label>';
                    html += '<div class="impulse-btn-group" data-name="align" style="width:100%;display:flex;gap:3px">';
                    html += '<button type="button" class="' + ((settings.align || 'center') === 'left' ? 'active' : '') + '" data-value="left" title="Left" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + ((settings.align || 'center') === 'center' ? 'active' : '') + '" data-value="center" title="Center" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="10" x2="6" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="18" y1="18" x2="6" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + ((settings.align || 'center') === 'right' ? 'active' : '') + '" data-value="right" title="Right" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="21" y1="10" x2="7" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="7" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + ((settings.align || 'center') === 'justify' ? 'active' : '') + '" data-value="justify" title="Justify" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="21" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="3" y2="18"/></svg></button>';
                    html += '<input type="hidden" name="align" value="' + (settings.align || 'center') + '">';
                    html += '</div>';
                    html += '</div>';
                    html += '<div style="flex:1">';
                    html += '<label style="font-size:11px;color:#888;margin-bottom:4px;display:block;text-align:right">Columns</label>';
                    html += '<div class="impulse-btn-group" data-name="columns" style="width:100%;display:flex;gap:3px">';
                    html += '<button type="button" class="' + ((settings.columns || '1') === '1' ? 'active' : '') + '" data-value="1" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">1</button>';
                    html += '<button type="button" class="' + ((settings.columns || '1') === '2' ? 'active' : '') + '" data-value="2" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">2</button>';
                    html += '<button type="button" class="' + ((settings.columns || '1') === '3' ? 'active' : '') + '" data-value="3" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">3</button>';
                    html += '<button type="button" class="' + ((settings.columns || '1') === '4' ? 'active' : '') + '" data-value="4" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">4</button>';
                    html += '<input type="hidden" name="columns" value="' + (settings.columns || '1') + '">';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';

                    

                    
                    
                    var _boxARaw = settings.box_align || '';
                    var _boxAEff = _boxARaw || (settings.align || 'center');
                    html += '<div class="impulse-setting-row" data-responsive="true" style="margin-top:6px">';
                    html += '<label style="font-size:11px;color:#888;margin-bottom:4px;display:block">Box position <span style="color:#666">(width &lt; 100%)</span></label>';
                    html += '<div class="impulse-btn-group" data-name="box_align" style="width:100%;display:flex;gap:3px">';
                    html += '<button type="button" class="' + (_boxAEff === 'left' ? 'active' : '') + '" data-value="left" title="Box left" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="5" width="18" height="14" rx="1" opacity="0.35"/><rect x="4" y="6" width="7" height="12" rx="1" fill="currentColor" stroke="none"/></svg></button>';
                    html += '<button type="button" class="' + (_boxAEff === 'center' ? 'active' : '') + '" data-value="center" title="Box center" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="5" width="18" height="14" rx="1" opacity="0.35"/><rect x="8.5" y="6" width="7" height="12" rx="1" fill="currentColor" stroke="none"/></svg></button>';
                    html += '<button type="button" class="' + (_boxAEff === 'right' ? 'active' : '') + '" data-value="right" title="Box right" style="flex:1;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="5" width="18" height="14" rx="1" opacity="0.35"/><rect x="13" y="6" width="7" height="12" rx="1" fill="currentColor" stroke="none"/></svg></button>';
                    html += '<input type="hidden" name="box_align" value="' + _boxARaw + '">';
                    html += '</div></div>';

                    

                    

                    
                    html += '<div style="display:flex;gap:12px;align-items:flex-end;margin-top:8px">';
                    html += '<div style="flex:1;min-width:0">' + settingFontPicker('font_family', settings.font_family || '').replace('margin-top:8px;', '') + '</div>';
                    html += '<div style="display:flex;gap:5px;align-items:center;flex-shrink:0">'
                        +   settingColorSwatchOnly('color', settings.color || '#666666', 'Text colour')
                        + '</div>';
                    html += '</div>';

                    

                    

                    
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('size', 'Font Size', settings, 16, 8, 120, 'px', true);
                    html += settingSliderR('line_height', 'Line Height', settings, 160, 100, 250, '%', true);
                    html += settingSliderR('letter_spacing', 'Spacing', settings, 0, -1, 5, 'px', true);
                    html += settingSliderR('width', 'Width', settings, 100, 10, 100, '%', true);
                    html += settingSliderR('text_halo', 'Halo', settings, 0, 0, 100, '%', true, 'Soft glow behind text for legibility on busy backgrounds');
                    html += settingSliderR('margin_top', 'Margin Top', settings, 0, 0, 100, 'px', true);
                    html += settingSliderR('padding_left', 'Padding Left', settings, 0, 0, 60, 'px', true);
                    html += settingSliderR('padding_right', 'Padding Right', settings, 0, 0, 60, 'px', true);
                    html += '</div>';

                    var colGapInactive = (!settings.columns || settings.columns === '1') ? 'display:none;' : '';
                    html += '<div class="impulse-column-gap-wrapper impulse-margin-grid" style="margin-top:8px;' + colGapInactive + '">' + settingSliderR('column_gap', 'Column Gap', settings, 30, 10, 60, 'px', true) + '</div>';

                    

                    

                    

                    

                    var _txtCols = settings.columns || '1';
                    var _heightHidden = (_txtCols === '1') ? 'display:none;' : '';
                    html += '<div class="impulse-text-height-wrapper impulse-margin-grid" style="margin-top:6px;' + _heightHidden + '">';
                    html += settingSliderR('min_height', 'Height', settings, 0, 0, 500, 'px', true, 'Fixed column flow height');
                    html += '<div></div><div></div><div></div>';
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    html += settingTextReveal(settings);
                    break;

                case 'image':
                    
                    html += '<div class="impulse-setting-row" style="display:flex;gap:6px;align-items:center">';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-select-image" style="width:auto;padding:0 12px;flex-shrink:0;height:26px">Select Image</button>';
                    html += '<button type="button" class="impulse-clear-image-btn" style="width:26px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.muted+';flex-shrink:0;box-sizing:border-box' + (!settings.image_id ? ';opacity:0.4;pointer-events:none' : '') + '" title="Clear Image"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                    html += '<input type="text" name="link" value="' + escapeHtml(settings.link || '') + '" placeholder="Link URL" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box;min-width:0">';
                    html += '<input type="hidden" name="image_id" value="' + (settings.image_id || '') + '">';
                    html += '</div>';

                    

                    
                    
                    var _useCut = !!(settings.use_cutout && settings.use_cutout != '0');
                    html += '<input type="hidden" name="use_cutout" value="' + (_useCut ? '1' : '0') + '">';
                    if (window.Impulse && Impulse.isStandalone) {
                        var _cutSrc = settings.image_src || settings.src || '';
                        var _cutSvg = /\.svg(\?|$)/i.test(_cutSrc);

                        

                        
                        var _cutDepth = !!(settings.depth_map);
                        var _cutOff = !settings.image_id || _cutSvg;
                        var _cutTip = _cutSvg ? 'Vector image (SVG): no background to remove' : '';
                        html += '<div class="impulse-setting-row" style="margin-top:6px">';
                        html += '<button type="button" class="impulse-img-cutout-btn" title="' + _cutTip + '" style="width:100%;height:26px;padding:0;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;font-size:11px;font-family:inherit;color:' + (_cutOff ? ImpC.dim : ImpC.text) + ';cursor:pointer;box-sizing:border-box' + (_cutOff ? ';pointer-events:none;opacity:0.5' : '') + '">' + (_useCut ? 'Restore background' : (_cutSvg ? 'Remove background (not for SVG)' : 'Remove background')) + '</button>';
                        html += '</div>';
                        html += '<div class="impulse-cutout-msg" style="display:none;font-size:10px;line-height:1.4;color:' + ImpC.dim + ';margin-top:4px"></div>';
                        if (_cutDepth) {
                            html += '<div class="impulse-cutout-depth-note" style="display:' + (_useCut ? 'none' : 'block') + ';font-size:10px;line-height:1.4;color:' + ImpC.dim + ';margin-top:4px">Removing the background turns off 3D depth.</div>';
                        }
                    }

                    

                    

                    
                    var _imgLightbox = !!settings.lightbox_enabled;
                    html += '<div class="impulse-setting-row" style="display:flex;align-items:center;gap:8px;margin-top:8px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:11px;color:'+ImpC.muted+'">';
                    html += '<input type="checkbox" name="lightbox_enabled" value="1"' + (_imgLightbox ? ' checked' : '') + ' style="margin:0">';
                    html += 'Open in lightbox</label>';
                    html += '<span style="font-size:11px;color:#666">(click to expand)</span>';
                    html += '</div>';

                    html += '<div id="impulse-image-lightbox-controls" style="' + (_imgLightbox ? '' : 'display:none') + '">';
                    
                    html += '<div class="impulse-section-divider" style="margin-top:10px">Thumbnail</div>';
                    html += settingBtnGroupFull('thumb_shape', '', settings.thumb_shape || 'circle', [
                        {v:'circle', l:'Circle'},
                        {v:'square', l:'Square'}
                    ]);
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('thumb_size', 'Size', settings, 96, 40, 300, 'px', true);
                    html += '<div></div>';
                    html += '</div>';
                    
                    html += '<div class="impulse-section-divider" style="margin-top:10px">Popup</div>';
                    html += settingBtnGroupFull('popup_shape', '', settings.popup_shape || 'rect', [
                        {v:'rect',   l:'Rectangle'},
                        {v:'circle', l:'Circle'}
                    ]);
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('popup_max_width', 'Max Width', settings, 900, 240, 1400, 'px', true);
                    html += '<div></div>';
                    html += '</div>';
                    
                    var _imgHoverLB = !!settings.hover
                        || (settings.trigger === 'hover' && settings.hover !== false);
                    html += '<div class="impulse-setting-row" style="margin-top:6px;display:flex;align-items:center;gap:8px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:11px;color:'+ImpC.muted+'">';
                    html += '<input type="checkbox" name="hover" value="1"' + (_imgHoverLB ? ' checked' : '') + ' style="margin:0">';
                    html += 'Open on hover</label>';
                    html += '<span style="font-size:11px;color:#666">(default: click)</span>';
                    html += '</div>';
                    
                    html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:10px">Border'
                        + '<span style="flex:1;height:1px;background:var(--imp-panel)"></span>'
                        + settingColorSwatchOnly('border_color_1', settings.border_color_1 || '#1d2327')
                        + settingColorSwatchOnly('border_color_2', settings.border_color_2 || '#cccccc')
                        + '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('border_speed', 'Speed', settings, 8, 2, 30, 's', true);
                    html += settingSliderR('border_width', 'Width', settings, 2, 1, 6, 'px', true);
                    html += '</div>';
                    html += '</div>'; 

                    html += '<div id="impulse-image-standard-controls" style="' + (_imgLightbox ? 'display:none' : '') + '">';

                    
                    
                    var _pinNow = !!settings.image_pin_to_screen;
                    html += '<div class="impulse-image-flow-only" style="' + (_pinNow ? 'display:none' : '') + '">';
                    
                    html += '<div class="impulse-setting-row" style="display:flex;align-items:center;gap:8px;margin-top:8px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:11px;color:'+ImpC.muted+'">';
                    html += '<input type="checkbox" name="fill_container" value="1"' + (settings.fill_container ? ' checked' : '') + ' style="margin:0">';
                    html += 'Fill Container</label>';
                    html += '<span style="font-size:11px;color:#666">(covers parent, may crop)</span>';
                    html += '</div>';

                    
                    
                    var _imgFp = settings.focal_point || '50% 50%';
                    var _imgFpPos = ['0% 0%','50% 0%','100% 0%','0% 50%','50% 50%','100% 50%','0% 100%','50% 100%','100% 100%'];
                    html += '<div id="impulse-image-focal" style="' + (settings.fill_container ? '' : 'display:none;') + 'margin-top:10px">';
                    html += '<div class="impulse-section-divider" style="margin-top:0">Focus</div>';
                    html += '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;max-width:96px">';
                    _imgFpPos.forEach(function(p){
                        html += '<button type="button" class="impulse-img-focal-btn" data-pos="' + p + '" title="' + p + '" style="height:24px;border-radius:3px;border:1px solid ' + ImpC.border + ';background:' + (p === _imgFp ? ImpC.text : ImpC.panel) + ';cursor:pointer;padding:0"></button>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="focal_point" value="' + escapeHtml(_imgFp) + '">';
                    html += '<p class="impulse-setting-hint" style="margin-top:6px">Switch the device tab to set focus per device.</p>';
                    html += '</div>';
                    
                    html += '<div id="impulse-image-size-controls" style="' + (settings.fill_container ? 'display:none' : '') + '">';
                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += settingSliderR('width', 'Width', settings, 50, 1, 100, '%', true);

                    html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 100, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('margin_top', 'Margin Top', settings, 0, 0, 100, 'px', true);
                    html += settingSliderR('margin_bottom', 'Margin Bottom', settings, 0, 0, 100, 'px', true);
                    html += '</div>';

                    
                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('flow_offset_y', 'Offset Y', settings, 0, -300, 300, 'px', true);
                    html += settingSliderR('flow_offset_x', 'Offset X', settings, 0, -300, 300, 'px', true);
                    html += '</div>';
                    html += '</div>';
                    html += '</div>'; 

                    
                    html += '<input type="hidden" name="image_radius_tl" value="' + (settings.image_radius_tl || 0) + '">';
                    html += '<input type="hidden" name="image_radius_tr" value="' + (settings.image_radius_tr || 0) + '">';
                    html += '<input type="hidden" name="image_radius_br" value="' + (settings.image_radius_br || 0) + '">';
                    html += '<input type="hidden" name="image_radius_bl" value="' + (settings.image_radius_bl || 0) + '">';

                    

                    

                    
                    
                    html += ImpulseCropBridge.renderHiddenInputs('image_crop_', settings);

                    

                    

                    var _imgCropOn = ImpulseCropBridge.hasCropApplied(settings, 'image_crop_', (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '');
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-image-crop-reset-btn" style="width:100%;height:26px;margin-top:10px;font-size:11px' + (_imgCropOn ? '' : ';display:none') + '">Reset Crop</button>';

                    

                    

                    

                    

                    

                    
                    
                    function _isShOn(v) {
                        if (v === undefined || v === null || v === '') return false;
                        return v !== '0' && v !== 0 && v !== false;
                    }
                    var _shSides = {
                        top:    _isShOn(settings.image_shadow_top),
                        right:  _isShOn(settings.image_shadow_right),
                        bottom: _isShOn(settings.image_shadow_bottom),
                        left:   _isShOn(settings.image_shadow_left)
                    };

                    if (!_shSides.top && !_shSides.right && !_shSides.bottom && !_shSides.left) {
                        var _legacySide = String(settings.image_shadow_side || '');
                        if (_shSides.hasOwnProperty(_legacySide)) _shSides[_legacySide] = true;
                    }
                    var _shTally = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"';
                    var _shSideIcons = {
                        left:   _shTally + '><path d="M4 4v16"/></svg>',
                        top:    _shTally + ' style="transform:rotate(90deg)"><path d="M4 4v16"/></svg>',
                        right:  _shTally + ' style="transform:rotate(180deg)"><path d="M4 4v16"/></svg>',
                        bottom: _shTally + ' style="transform:rotate(270deg)"><path d="M4 4v16"/></svg>'
                    };
                    html += '<div style="display:flex;align-items:center;gap:8px;margin-top:10px;margin-bottom:6px">';
                    html += '<label style="font-size:11px;color:#888">Shadow Edge</label>';
                    html += '<div class="impulse-image-shadow-sides impulse-btn-group" style="display:flex;align-items:center;gap:3px;margin-left:auto">';
                    ['left','top','right','bottom'].forEach(function(side) {
                        var act = _shSides[side];
                        html += '<button type="button" class="impulse-image-shadow-side-btn' + (act ? ' active' : '') + '" data-side="' + side + '" title="' + side.charAt(0).toUpperCase() + side.slice(1) + '" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box">' + _shSideIcons[side] + '</button>';
                    });
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('image_shadow_strength', 'Depth', settings, 40, 0, 100, '%',  true);
                    html += settingSliderR('image_shadow_blur',     'Soft',  settings, 12, 0, 50,  'px', true);
                    html += '</div>';

                    html += '<input type="hidden" name="image_shadow_top"    value="' + (_shSides.top    ? '1' : '0') + '">';
                    html += '<input type="hidden" name="image_shadow_right"  value="' + (_shSides.right  ? '1' : '0') + '">';
                    html += '<input type="hidden" name="image_shadow_bottom" value="' + (_shSides.bottom ? '1' : '0') + '">';
                    html += '<input type="hidden" name="image_shadow_left"   value="' + (_shSides.left   ? '1' : '0') + '">';
                    html += '<input type="hidden" name="image_shadow_side"   value="">';

                    

                    

                    

                    

                    var _imgPin = !!settings.image_pin_to_screen;
                    html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:14px">Pin to screen';
                    html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:'+ImpC.panel+'"></span>';
                    html += '<input type="checkbox" name="image_pin_to_screen" value="1"' + (_imgPin ? ' checked' : '') + '>';
                    html += '</div>';

                    

                    
                    html += '<div id="impulse-image-pin-controls" style="display:' + (_imgPin ? 'block' : 'none') + ';margin-top:6px">';
                    var _imgHA = settings.image_h_align || 'center';
                    var _imgVA = settings.image_v_align || 'center';
                    var _imgColMap = ['left','center','right'];
                    var _imgRowMap = ['top','center','bottom'];
                    html += '<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">';
                    html += '<label style="font-size:11px;color:#888">Anchor</label>';
                    html += '<div class="impulse-align-grid" data-name="image_anchor" style="flex-shrink:0">';
                    for (var _imgR = 0; _imgR < 3; _imgR++) {
                        for (var _imgC = 0; _imgC < 3; _imgC++) {
                            var _dHA = _imgColMap[_imgC];
                            var _dVA = _imgRowMap[_imgR];
                            var _dAct = (_imgHA === _dHA && _imgVA === _dVA);
                            html += '<button type="button" class="impulse-align-dot' + (_dAct ? ' active' : '') + '" data-ca="' + _dHA + '" data-va="' + _dVA + '" data-target="image"></button>';
                        }
                    }
                    html += '</div>';
                    html += '</div>';
                    
                    var _imgAnchorSfx = (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '';
                    html += '<input type="hidden" name="image_h_align' + _imgAnchorSfx + '" value="' + _imgHA + '">';
                    html += '<input type="hidden" name="image_v_align' + _imgAnchorSfx + '" value="' + _imgVA + '">';
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('image_offset_x', 'Offset X', settings, 0, -50, 50, 'vw', true);
                    html += settingSliderR('image_offset_y', 'Offset Y', settings, 0, -50, 50, 'vh', true);
                    html += '</div>';
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('image_size_min',   'Min',   settings, 100, 20, 1000, 'px', true);
                    html += settingSliderR('image_size_fluid', 'Fluid', settings,  30,  5,  100, 'vw', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('image_size_max',   'Max',   settings, 600, 50, 2000, 'px', true);
                    html += settingSliderR('image_z',          'Layer', settings,   0,  0,   10, '',   true);
                    html += '</div>';
                    html += '</div>'; 

                    html += '<div class="impulse-section-divider" style="margin-top:10px">Hover Effect</div>';
                    var imgHover = settings.hover_effect || 'none';

                    html += '<div class="impulse-btn-group" data-name="hover_effect" data-toggleable="1" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px;margin-top:4px">';
                    [{v:'shine',l:'Shine'},{v:'slices',l:'Slices'},{v:'tilt3d',l:'Tilt 3D'},{v:'portal',l:'Portal'},{v:'burn',l:'Burn'},{v:'thermal',l:'Thermal'}].forEach(function(e) {
                        html += '<button type="button" class="impulse-effect-btn' + (imgHover === e.v ? ' active' : '') + '" data-value="' + e.v + '">' + e.l + '</button>';
                    });
                    html += '<input type="hidden" name="hover_effect" value="' + imgHover + '">';
                    html += '</div>';

                    

                    

                    
                    var _imgDepthMap = settings.depth_map || '';
                    var _imgDepthStr = parseInt(settings.depth_strength) || 50;
                    var _hasImgSrc = !!(settings.image_src || settings.src);
                    var _depthAvail = !!(window.Impulse && Impulse.isStandalone);
                    var _showDepthSection = _depthAvail || !!_imgDepthMap;
                    html += '<input type="hidden" name="image_src" value="' + escapeHtml(settings.image_src || settings.src || '') + '">';
                    html += '<input type="hidden" name="depth_map" value="' + escapeHtml(_imgDepthMap) + '">';
                    if (_showDepthSection) {
                        html += '<div class="impulse-section-divider" style="margin-top:10px">3D Depth</div>';

                        
                        
                        html += '<div class="impulse-img-depth-offmsg" style="display:' + (_useCut ? 'block' : 'none') + ';font-size:10px;line-height:1.4;color:'+ImpC.dim+';margin-top:4px">3D depth is off while the background is removed. Restore the background to use it.</div>';
                        html += '<div class="impulse-img-depth-wrap" style="display:' + (_useCut ? 'none' : 'block') + '">';
                        if (!_imgDepthMap) {
                            var _depthOff = !_hasImgSrc;
                            html += '<button type="button" class="impulse-img-depth-generate-btn" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:' + (_depthOff ? ''+ImpC.dim+'' : ''+ImpC.text+'') + ';cursor:pointer' + (_depthOff ? ';pointer-events:none;opacity:0.5' : '') + '">Generate Depth</button>';
                        } else {
                            
                            html += '<div class="impulse-margin-grid" style="margin-top:4px">';
                            html += settingSliderR('depth_strength', 'Strength', settings, 50, 0, 100, '', true);
                            html += '<div></div>';
                            html += '</div>';
                        }
                        html += '</div>';
                    }
                    html += '</div>'; 

                    html += settingEntranceAnimation(settings);
                    break;

                

                case 'video':
                    var hasFile = !!(settings.video_file_url);
                    var hasPoster = !!(settings.poster_url);
                    
                    html += '<div class="impulse-video-url-row" style="display:' + (hasFile ? 'none' : 'block') + '">';
                    html += '<input type="text" name="video_url" value="' + escapeHtml(settings.video_url || '') + '" placeholder="Video URL" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '</div>';
                    
                    html += '<div class="impulse-video-file-row" style="display:' + (hasFile ? 'flex' : 'none') + ';gap:5px;align-items:center">';
                    html += '<span style="flex:1;min-width:0;font-size:11px;color:'+ImpC.muted+';overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escapeHtml((settings.video_file_url || '').split('/').pop()) + '</span>';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-remove-video-file" style="height:26px;padding:0 10px;flex-shrink:0">Remove</button>';
                    html += '</div>';
                    
                    html += '<div style="display:flex;gap:5px;margin-top:5px">';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-select-video-file" style="flex:1;height:26px;padding:0;box-sizing:border-box">Select File</button>';
                    
                    html += '<div style="flex:1;min-width:0">';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-select-poster" style="width:100%;height:26px;padding:0;box-sizing:border-box;display:' + (hasPoster ? 'none' : 'block') + '">Poster</button>';
                    html += '<div id="impulse-poster-preview" style="display:' + (hasPoster ? 'flex' : 'none') + ';align-items:center;gap:4px;height:26px">';
                    html += '<img src="' + (settings.poster_url || '') + '" style="width:40px;height:26px;object-fit:cover;border-radius:3px;border:1px solid '+ImpC.border+';flex-shrink:0">';
                    html += '<span style="flex:1;font-size:11px;color:#888">Poster</span>';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-remove-poster" style="height:20px;padding:0 6px;flex-shrink:0;font-size:10px">✕</button>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                    html += '<input type="hidden" name="poster_id" value="' + (settings.poster_id || '') + '">';
                    html += '<input type="hidden" name="poster_url" value="' + (settings.poster_url || '') + '">';
                    
                    var videoThumb = '';
                    var vUrl = settings.video_url || '';
                    var ytMatch = vUrl.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
                    if (ytMatch) videoThumb = 'https://img.youtube.com/vi/' + ytMatch[1] + '/hqdefault.jpg';
                    html += '<div class="impulse-video-thumb-preview" style="display:' + (videoThumb ? 'block' : 'none') + ';margin-top:5px">';
                    html += '<img src="' + videoThumb + '" style="width:100%;border-radius:4px;border:1px solid '+ImpC.border+';display:block">';
                    html += '</div>';
                    
                    var hasMask = !!(settings.mask_id && settings.mask_url);
                    var aspectVal = settings.aspect_ratio || '16:9';
                    html += '<div class="impulse-video-aspect-row" style="display:' + (hasMask || hasFile ? 'none' : 'block') + ';margin-top:5px">';
                    html += '<div class="impulse-btn-group" data-name="aspect_ratio" style="display:flex;width:100%;gap:5px">';
                    ['16:9','4:3','21:9','1:1','9:16'].forEach(function(a) {
                        html += '<button type="button" data-value="' + a + '" class="' + (aspectVal === a ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + a + '</button>';
                    });
                    html += '<input type="hidden" name="aspect_ratio" value="' + aspectVal + '">';
                    html += '</div></div>';
                    
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="autoplay"' + (settings.autoplay ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"><span>Autoplay</span></label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><span>Controls</span><input type="checkbox" name="controls"' + (settings.controls !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '</div>';

                    

                    

                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += settingSliderR('width', 'Width', settings, 30, 20, 100, '%', true);
                    html += '</div>';

                    
                    html += ImpulseCropBridge.renderHiddenInputs('video_crop_', settings);

                    html += '<input type="hidden" name="video_radius_tl" value="' + (settings.video_radius_tl || 0) + '">';
                    html += '<input type="hidden" name="video_radius_tr" value="' + (settings.video_radius_tr || 0) + '">';
                    html += '<input type="hidden" name="video_radius_br" value="' + (settings.video_radius_br || 0) + '">';
                    html += '<input type="hidden" name="video_radius_bl" value="' + (settings.video_radius_bl || 0) + '">';

                    
                    
                    var _vidCropOn = ImpulseCropBridge.hasCropApplied(settings, 'video_crop_', (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '');
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-image-crop-reset-btn" style="width:100%;height:26px;margin-top:10px;font-size:11px' + (_vidCropOn ? '' : ';display:none') + '">Reset Crop</button>';
                    html += settingEntranceAnimation(settings);
                    break;
                    
                case 'button':

                    
                    
                    html += '<div class="impulse-inline-right" style="margin-top:8px">';
                    html += '<label style="font-size:11px">Text</label>';
                    html += '<input type="text" name="text" value="' + escapeHtml(settings.text || '') + '" placeholder="Click Here" style="width:160px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '</div>';
                    html += '<div class="impulse-inline-right" style="margin-top:6px">';
                    html += '<label style="font-size:11px">URL</label>';
                    html += '<input type="text" name="url" value="' + escapeHtml(settings.url || '#') + '" style="width:160px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '</div>';

                    

                    
                    var _osScreens = [];
                    try {
                        var _osIfr = document.getElementById('impulse-iframe');
                        var _osDoc = _osIfr && (_osIfr.contentDocument || (_osIfr.contentWindow && _osIfr.contentWindow.document));
                        if (_osDoc) {
                            _osDoc.querySelectorAll('.impulse-el[data-type="section"][data-screen-skip="1"]').forEach(function(s) {
                                var _id = s.getAttribute('data-id');
                                if (!_id) return;
                                var _h = s.querySelector('.impulse-el[data-type="title"], .impulse-el[data-type="heading"], h1,h2,h3');
                                var _lbl = (_h && _h.textContent ? _h.textContent.trim() : '').slice(0, 40) || ('Section ' + _id);
                                _osScreens.push({id: _id, label: _lbl});
                            });
                        }
                    } catch (_e) {}
                    var _osCur = String(settings.open_screen_id || '');
                    html += '<div class="impulse-inline-right" style="margin-top:6px">';
                    html += '<label style="font-size:11px" title="Reveal a Reveal-on-click section on click. Overrides URL.">Open screen</label>';
                    html += '<select name="open_screen_id" style="width:160px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '<option value=""' + (_osCur === '' ? ' selected' : '') + '>None (use URL)</option>';
                    if (_osScreens.length === 0) {
                        html += '<option value="" disabled>(mark a section "Reveal on click only" first)</option>';
                    } else {
                        _osScreens.forEach(function(o) {
                            html += '<option value="' + o.id + '"' + (_osCur === o.id ? ' selected' : '') + '>' + escapeHtml(o.label) + '</option>';
                        });
                    }
                    html += '</select>';
                    html += '</div>';
                    
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="new_tab" class="impulse-checkbox"' + (settings.new_tab ? ' checked' : '') + '><span>Open in New Tab</span></label>';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-select-button-icon" style="height:26px;padding:0 12px;box-sizing:border-box">Select Icon</button>';
                    html += '<input type="hidden" name="icon" value="' + (settings.icon || '') + '">';
                    html += '</div>';

                    var noIcon = !settings.icon;
                    html += '<div style="margin-top:6px;' + (noIcon ? 'opacity:0.4;pointer-events:none;' : '') + '">';
                    html += settingBtnGroup('icon_position', 'Icon Position', settings.icon_position || 'before', [
                        {v:'before',l:'Before'},{v:'after',l:'After'}
                    ]);
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('icon_spacing', 'Icon Spacing', settings, 8, 0, 20, 'px', true);
                    html += settingSliderR('icon_size', 'Icon Size', settings, 0, 20, 40, 'px', true);
                    html += '</div>';
                    html += '</div>';

                    
                    
                    html += '<div style="margin-top:12px">';
                    var alignVal = getResponsiveValue(settings, 'align', 'center');
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="align" style="display:flex;width:100%;gap:3px">';
                    html += '<button type="button" data-value="left" class="' + (alignVal === 'left' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Left</button>';
                    html += '<button type="button" data-value="center" class="' + (alignVal === 'center' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Center</button>';
                    html += '<button type="button" data-value="right" class="' + (alignVal === 'right' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Right</button>';
                    html += '<button type="button" data-value="full" class="' + (alignVal === 'full' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Full Width</button>';
                    html += '<input type="hidden" name="align" value="' + alignVal + '">';
                    html += '</div>';
                    html += '</div>';

                    

                    
                    html += '<div style="margin-top:8px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="frosted_glass" class="impulse-checkbox"' + (settings.frosted_glass ? ' checked' : '') + '><span>Frosted glass</span></label>';
                    html += '</div>';

                    
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px">';
                    html += '<div style="text-align:left">'  + settingColorSwatch('text_color', 'Text',       settings.text_color || '#ffffff') + '</div>';
                    html += '<div style="text-align:right">' + settingColorSwatch('bg_color',   'Background', settings.bg_color   || ''+ImpC.surface2+'') + '</div>';
                    html += '</div>';

                    

                    
                    var _btnWeightVal = parseInt(getResponsiveValue(settings, 'weight', 700)) || 700;
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('btn_height', 'Height', settings, 44, 28, 80, 'px', true);
                    html += settingSlider('weight', 'Weight', _btnWeightVal, 100, 900, '', true, true, 700, undefined, 100);

                    

                    

                    html += settingSliderR('btn_min_width', 'Width', settings, 0, 0, 400, 'px', true, 'Fixed button width. 0 = intrinsic (text-driven). Any positive value locks all buttons in a row to that width — pick a value that fits your longest label.');

                    
                    html += settingSliderR('text_halo', 'Halo', settings, 0, 0, 100, '%', true, 'Soft glow behind the button label for legibility on busy backgrounds');
                    html += '</div>';

                    

                    
                    
                    var gradTo = getResponsiveValue(settings, 'border_gradient_to', '');
                    html += '<div style="margin-top:6px">';
                    html += '<div class="impulse-section-divider impulse-divider-with-toggle" style="margin-top:14px">';
                    html += '<span>Border</span>';
                    html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
                    html += '<div style="display:flex;align-items:center;gap:5px;flex-shrink:0">';
                    html +=     settingColorSwatchOnly('border_color',        settings.border_color || ''+ImpC.surface2+'', 'Border');
                    html +=     settingColorSwap('border_color', 'border_gradient_to', 'Swap border ↔ gradient');
                    html +=     settingColorSwatchOnly('border_gradient_to',  gradTo,                                      'Gradient');
                    html += '</div>';
                    html += '</div>';

                    

                    

                    

                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('border_width',          'Width',      settings, 0,   0, 5,   'px',  true);
                    html += settingSliderR('border_spin_speed',     'Spin',       settings, 30,  0, 180, '°/s', true);
                    html += settingSliderR('border_mouse_sens',     'Mouse sens', settings, 0,   0, 100, '%',   true);
                    html += settingSliderR('border_radius',         'Radius',     settings, 6,   0, 60,  'px',  true);
                    html += '</div>';
                    html += '</div>';
                    html += settingEntranceAnimation(settings);
                    break;
                    
                case 'schedule': {

                    

                    var _scInp = 'width:100%;height:28px;padding:5px 8px;border:1px solid ' + ImpC.border + ';border-radius:3px;font-size:12px;background:' + ImpC.panel + ';color:' + ImpC.text + ';box-sizing:border-box';
                    var _scLbl = 'display:block;margin-bottom:4px;font-size:11px;color:#888;white-space:nowrap';
                    html += '<div class="impulse-section-divider" style="margin-top:0">Timetable</div>';
                    html += '<div style="margin-bottom:8px"><label style="' + _scLbl + '">Title</label><input type="text" name="title" value="' + escapeHtml(settings.title || '') + '" placeholder="This week" style="' + _scInp + '"></div>';
                    html += '<div style="display:flex;gap:8px;margin-bottom:8px">';
                    html += '<div style="flex:1"><label style="' + _scLbl + '">Days ahead</label><input type="text" name="days_ahead" value="' + escapeHtml((settings.days_ahead != null ? settings.days_ahead : 7).toString()) + '" placeholder="7" style="' + _scInp + '"></div>';
                    html += '<div style="flex:1"><label style="' + _scLbl + '">Max width</label><input type="text" name="max_width" value="' + escapeHtml((settings.max_width != null ? settings.max_width : 940).toString()) + '" placeholder="940" style="' + _scInp + '"></div>';
                    html += '</div>';
                    html += '<div class="impulse-section-divider">Colors</div>';
                    html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:8px">';
                    html += '<div style="text-align:left">'   + settingColorSwatch('card_bg', 'Cell', settings.card_bg || '#ffffff') + '</div>';
                    html += '<div style="text-align:center">' + settingColorSwatch('accent_color', 'Accent', settings.accent_color || '#0e0f12') + '</div>';
                    html += '<div style="text-align:center">' + settingColorSwatch('accent_text', 'Btn text', settings.accent_text || '#ffffff') + '</div>';
                    html += '<div style="text-align:right">'  + settingColorSwatch('border_color', 'Border', settings.border_color || '#e5e7eb') + '</div>';
                    html += '</div>';
                    break;
                }

                case 'reviews': {

                    

                    var _rvList = [];
                    try {
                        var _rvRaw = settings.reviews;
                        if (_rvRaw) _rvList = (typeof _rvRaw === 'string') ? JSON.parse(_rvRaw) : _rvRaw;
                    } catch (e) { _rvList = []; }
                    if (!Array.isArray(_rvList)) _rvList = [];

                    var _rvCols   = (settings.columns || '3').toString();
                    var _rvAlign  = settings.align || 'center';
                    var _rvHeader = (settings.show_header === '0' || settings.show_header === false) ? '0' : '1';

                    
                    var _rvInp = 'width:100%;height:28px;padding:5px 8px;border:1px solid ' + ImpC.border + ';border-radius:3px;font-size:12px;background:' + ImpC.panel + ';color:' + ImpC.text + ';box-sizing:border-box';
                    var _rvLbl = 'display:block;margin-bottom:4px;font-size:11px;color:#888;white-space:nowrap';
                    var rvField = function (n, l, v, ph) {
                        return '<div style="margin-bottom:8px"><label style="' + _rvLbl + '">' + l + '</label>'
                             + '<input type="text" name="' + n + '" value="' + escapeHtml(v || '') + '" placeholder="' + escapeHtml(ph || '') + '" style="' + _rvInp + '"></div>';
                    };
                    html += '<div class="impulse-section-divider" style="margin-top:0">Google profile</div>';
                    html += rvField('business_name', 'Business name', settings.business_name, 'Cela Glow');
                    html += rvField('profile_url', 'All-reviews URL', settings.profile_url, 'https://g.page/...');
                    html += rvField('write_url', 'Write-review URL', settings.write_url, 'https://g.page/r/.../review');
                    
                    html += '<div style="display:flex;gap:8px;margin-bottom:8px">';
                    html += '<div style="flex:1"><label style="' + _rvLbl + '">Rating</label><input type="text" name="rating" value="' + escapeHtml(settings.rating || '') + '" placeholder="4.9" style="' + _rvInp + '"></div>';
                    html += '<div style="flex:1"><label style="' + _rvLbl + '">Total reviews</label><input type="text" name="review_count" value="' + escapeHtml(settings.review_count || '') + '" placeholder="124" style="' + _rvInp + '"></div>';
                    html += '</div>';

                    html += '<div class="impulse-section-divider">Header</div>';
                    html += '<div class="impulse-btn-group" data-name="show_header" style="display:grid;grid-template-columns:1fr 1fr;gap:3px;margin-bottom:8px">';
                    html += '<button type="button" class="impulse-la-preset-btn' + (_rvHeader === '1' ? ' active' : '') + '" data-value="1">Show</button>';
                    html += '<button type="button" class="impulse-la-preset-btn' + (_rvHeader === '0' ? ' active' : '') + '" data-value="0">Hide</button>';
                    html += '<input type="hidden" name="show_header" value="' + _rvHeader + '">';
                    html += '</div>';

                    html += '<div class="impulse-section-divider">Columns</div>';
                    html += '<div class="impulse-btn-group" data-name="columns" style="display:grid;grid-template-columns:repeat(3,1fr);gap:3px;margin-bottom:8px">';
                    ['1', '2', '3'].forEach(function(c) {
                        html += '<button type="button" class="impulse-la-preset-btn' + (_rvCols === c ? ' active' : '') + '" data-value="' + c + '">' + c + '</button>';
                    });
                    html += '<input type="hidden" name="columns" value="' + _rvCols + '">';
                    html += '</div>';

                    html += '<div class="impulse-section-divider">Align</div>';
                    html += '<div class="impulse-btn-group" data-name="align" style="display:grid;grid-template-columns:repeat(3,1fr);gap:3px;margin-bottom:8px">';
                    [['left', 'Left'], ['center', 'Center'], ['right', 'Right']].forEach(function(o) {
                        html += '<button type="button" class="impulse-la-preset-btn' + (_rvAlign === o[0] ? ' active' : '') + '" data-value="' + o[0] + '">' + o[1] + '</button>';
                    });
                    html += '<input type="hidden" name="align" value="' + escapeHtml(_rvAlign) + '">';
                    html += '</div>';

                    

                    

                    html += '<div class="impulse-section-divider">Colors</div>';
                    html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:8px">';
                    html += '<div style="text-align:left">'   + settingColorSwatch('accent_color', 'Accent', settings.accent_color || '#1a73e8') + '</div>';
                    html += '<div style="text-align:center">' + settingColorSwatch('star_color', 'Stars', settings.star_color || '#fbbc04') + '</div>';
                    html += '<div style="text-align:center">' + settingColorSwatch('card_bg', 'Card', settings.card_bg || '#ffffff') + '</div>';
                    html += '<div style="text-align:right">'  + settingColorSwatch('text_color', 'Text', settings.text_color || '#1f2937') + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-section-divider">Reviews</div>';
                    html += '<input type="hidden" name="reviews" value="' + escapeHtml(JSON.stringify(_rvList)) + '">';
                    html += '<div class="impulse-reviews-list" style="display:flex;flex-direction:column;gap:8px;margin-bottom:8px">';
                    _rvList.forEach(function(r) { html += impulseReviewRow(r); });
                    html += '</div>';
                    html += '<button type="button" id="impulse-add-review" class="instinctor-btn instinctor-btn-sm" style="width:100%;height:28px">+ Add review</button>';
                    html += '<div style="font-size:10px;color:' + ImpC.dim + ';line-height:1.4;margin-top:6px">Use real Google reviews only. Paste each review\'s text, the reviewer name, and a star rating.</div>';
                    break;
                }

                case 'icon_card':
                    
                    html += '<div style="display:flex;gap:6px">';
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-select-icon" style="flex:1">Icon</button>';
                    
                    html += '<button type="button" class="instinctor-btn instinctor-btn-sm" id="impulse-upload-icon-image" style="flex:1">Image</button>';
                    html += '<input type="hidden" name="icon" value="' + (settings.icon || 'star') + '">';
                    html += '<input type="hidden" name="icon_image" value="' + (settings.icon_image || '') + '">';
                    html += '</div>';
                    
                    if (settings.icon_image) {
                        html += '<div class="impulse-icon-image-preview" style="display:flex;align-items:center;gap:8px;margin-top:6px">';
                        html += '<img src="' + settings.icon_image + '" style="width:32px;height:32px;object-fit:contain;border-radius:4px;border:1px solid '+ImpC.border+'">';
                        html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-remove-icon-image" style="height:26px;padding:0 12px;box-sizing:border-box;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.muted+';font-size:11px">Remove</button>';
                        html += '</div>';
                    }

                    var hideAlignForHorizontal = (settings.text_position === 'left' || settings.text_position === 'right');
                    html += '<div class="impulse-icon-layout-settings" style="display:' + (settings.title_content || settings.text_content ? 'block' : 'none') + ';margin-top:6px">';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="text_position" style="display:flex;width:100%;gap:6px">';
                    html += '<button type="button" data-value="below" class="' + ((settings.text_position || 'below') === 'below' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Below</button>';
                    html += '<button type="button" data-value="above" class="' + ((settings.text_position || 'below') === 'above' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Above</button>';
                    html += '<button type="button" data-value="left" class="' + ((settings.text_position || 'below') === 'left' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Left</button>';
                    html += '<button type="button" data-value="right" class="' + ((settings.text_position || 'below') === 'right' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Right</button>';
                    html += '<input type="hidden" name="text_position" value="' + (settings.text_position || 'below') + '">';
                    html += '</div>';
                    html += '<div class="impulse-icon-valign-settings" style="display:' + (hideAlignForHorizontal ? 'block' : 'none') + ';margin-top:6px">';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="valign" style="display:flex;width:100%;gap:6px">';
                    html += '<button type="button" data-value="top" class="' + ((settings.valign || 'center') === 'top' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Top</button>';
                    html += '<button type="button" data-value="center" class="' + ((settings.valign || 'center') === 'center' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Center</button>';
                    html += '<button type="button" data-value="bottom" class="' + ((settings.valign || 'center') === 'bottom' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Bottom</button>';
                    html += '<input type="hidden" name="valign" value="' + (settings.valign || 'center') + '">';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="impulse-icon-align-settings" style="display:' + (hideAlignForHorizontal ? 'none' : 'block') + ';margin-top:6px">';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="align" style="display:flex;width:100%;gap:6px">';
                    html += '<button type="button" data-value="left" class="' + ((settings.align || 'center') === 'left' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Left</button>';
                    html += '<button type="button" data-value="center" class="' + ((settings.align || 'center') === 'center' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Center</button>';
                    html += '<button type="button" data-value="right" class="' + ((settings.align || 'center') === 'right' ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Right</button>';
                    html += '<input type="hidden" name="align" value="' + (settings.align || 'center') + '">';
                    html += '</div>';
                    html += '</div>';

                    html += '<input type="text" name="title_content" value="' + escapeHtml(settings.title_content || '') + '" placeholder="Title" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box;margin-top:6px">';
                    html += '<textarea name="text_content" placeholder="Description" rows="2" style="width:100%;min-height:52px;padding:6px 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box;font-family:inherit;resize:vertical;margin-top:6px">' + escapeHtml(settings.text_content || '') + '</textarea>';

                    html += '<div style="display:flex;align-items:center;gap:8px;margin-top:6px">';
                    html += '<input type="text" name="link" value="' + escapeHtml(settings.link || '') + '" placeholder="Link URL" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer;white-space:nowrap"><span>New Tab</span><input type="checkbox" name="new_tab" class="impulse-checkbox"' + (settings.new_tab ? ' checked' : '') + '></label>';
                    html += '</div>';

                    
                    var cellBase = 'flex:0 0 26px;width:26px;display:flex;flex-direction:column;gap:4px';
                    var lblBase  = 'font-size:11px;color:'+ImpC.muted+';white-space:nowrap;overflow:visible';
                    html += '<div style="display:flex;justify-content:space-between;margin-top:6px">';
                    html += '<div style="' + cellBase + ';align-items:flex-start"><div style="' + lblBase + ';text-align:left">Icon</div>' + settingColorSwatchOnly('color', settings.color || '#666666') + '</div>';
                    html += '<div style="' + cellBase + ';align-items:flex-end"><div style="' + lblBase + ';text-align:right">Text</div>' + settingColorSwatchOnly('text_color', settings.text_color || '#666666') + '</div>';
                    html += '</div>';

                    

                    

                    var iconHoverFx = settings.hover_effect || 'parallax';
                    html += '<div class="impulse-section-divider" style="margin-top:10px">Hover</div>';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="hover_effect" style="display:flex;width:100%;gap:3px">';
                    [{v:'none',l:'None'},{v:'parallax',l:'Parallax'},{v:'lift',l:'Lift'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (iconHoverFx === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="hover_effect" value="' + iconHoverFx + '">';
                    html += '</div>';

                    
                    
                    var sizeMax = settings.icon_image ? 200 : 128;
                    var sizeMin = settings.icon_image ? 50 : 16;
                    var sizeLabel = settings.icon_image ? 'Image' : 'Icon';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('padding', 'Padding', settings, 16, 0, 48, 'px', false);
                    html += settingSliderR('size', sizeLabel, settings, 48, sizeMin, sizeMax, 'px', true);
                    html += settingSliderR('border_radius', 'Radius', settings, 50, 0, 50, '%', false);
                    html += settingSliderR('title_size', 'Title', settings, 18, 12, 48, 'px', true);
                    html += settingSliderR('border_width', 'Stroke', settings, 0, 0, 6, 'px', false);
                    html += settingSliderR('text_size', 'Text', settings, 14, 8, 32, 'px', true);

                    
                    
                    html += settingSliderR('text_halo', 'Halo', settings, 0, 0, 100, '%', true, 'Soft glow behind icon + text for legibility on busy backgrounds');
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    break;

                case 'divider':

                    

                    

                    
                    var divOrient = settings.orientation || 'horizontal';
                    html += '<div class="impulse-btn-group" data-name="orientation" style="display:grid;grid-template-columns:1fr 1fr;gap:3px;margin-top:6px">';
                    html += '<button type="button" data-value="horizontal" class="' + (divOrient === 'horizontal' ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box;display:flex;align-items:center;justify-content:center;gap:6px"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 12h16"/></svg>Horizontal</button>';
                    html += '<button type="button" data-value="vertical" class="' + (divOrient === 'vertical' ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box;display:flex;align-items:center;justify-content:center;gap:6px"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 4v16"/></svg>Vertical</button>';
                    html += '<input type="hidden" name="orientation" value="' + divOrient + '">';
                    html += '</div>';

                    var divStyle = settings.style || 'neon';
                    html += '<div class="impulse-btn-group" data-name="style" style="display:grid;grid-template-columns:repeat(3,1fr);gap:3px;margin-top:6px">';
                    [
                        {v:'neon',l:'Neon'},{v:'electric',l:'Electric'},{v:'glow_scan',l:'Scan'},
                        {v:'aurora',l:'Aurora'},{v:'prism',l:'Prism'},{v:'stripes',l:'Stripes'}
                    ].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (divStyle === o.v ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="style" value="' + divStyle + '">';
                    html += '</div>';

                    

                    
                    var dualColorStyles = ['aurora', 'stripes'];
                    var showColor2 = dualColorStyles.indexOf(divStyle) !== -1;
                    var pAlignVal = settings.position_align || 'center';
                    html += '<div style="display:grid;grid-template-columns:1fr auto 1fr;gap:8px;margin-top:8px;align-items:start">';
                    html += '<div>' + settingColorSwatch('color', 'Color 1', settings.color || '#00aaff') + '</div>';
                    html += '<div style="text-align:center"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Position</label>';
                    html += '<div class="impulse-btn-group" data-name="position_align" style="display:flex;gap:2px">';
                    html += '<button type="button" class="' + (pAlignVal === 'left' ? 'active' : '') + '" data-value="left" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12H3m0 0 4-4m-4 4 4 4"/></svg></button>';
                    html += '<button type="button" class="' + (pAlignVal === 'center' ? 'active' : '') + '" data-value="center" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 3v18M3 12h18"/></svg></button>';
                    html += '<button type="button" class="' + (pAlignVal === 'right' ? 'active' : '') + '" data-value="right" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 12h18m0 0-4-4m4 4-4 4"/></svg></button>';
                    html += '<input type="hidden" name="position_align" value="' + pAlignVal + '">';
                    html += '</div></div>';
                    html += '<div style="text-align:right;' + (showColor2 ? '' : 'opacity:0.3;pointer-events:none;') + '"><div style="display:flex;justify-content:flex-end">' + settingColorSwatch('color2', 'Color 2', settings.color2 || '#00ffff') + '</div></div>';
                    html += '</div>';

                    

                    

                    
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    var _thickHtml = settingSliderR('thickness', 'Thickness', settings, 2, 1, 6, 'px', true);
                    if (divStyle === 'neon') {
                        html += '<div style="opacity:0.6;pointer-events:none" title="Thickness is fixed for Neon — tube size is built into the effect">' + _thickHtml.replace('<input type="range"', '<input type="range" disabled') + '</div>';
                    } else {
                        html += _thickHtml;
                    }
                    html += '<div class="divider-horiz-only" style="display:' + (divOrient === 'vertical' ? 'none' : 'block') + '">' + settingSliderR('width', 'Width', settings, 100, 10, 100, '%', true) + '</div>';
                    html += '<div class="divider-vert-only"  style="display:' + (divOrient === 'vertical' ? 'block' : 'none') + '">' + settingSliderR('height_px', 'Height', settings, 200, 40, 1000, 'px', true) + '</div>';
                    html += '</div>';

                    
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('tilt', 'Tilt 3D', settings, 0, 0, 30, '°', true);
                    html += '<div style="display:grid;grid-template-rows:14px 18px;row-gap:6px;justify-items:end">';
                    html += '<label style="font-size:11px;color:'+ImpC.muted+';line-height:14px;align-self:center;margin:0">Fade Edges</label>';
                    html += '<input type="checkbox" name="fade_edges"' + (settings.fade_edges ? ' checked' : '') + ' style="margin:0;width:14px;height:14px;cursor:pointer;align-self:center">';
                    html += '</div>';
                    html += '</div>';

                    html += '<div class="impulse-inline-right" style="margin-top:8px">';
                    html += '<label style="font-size:11px">Label</label>';
                    html += '<input type="text" name="label" value="' + escapeHtml(settings.label || '') + '" placeholder="OR, CHAPTER…" style="width:160px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '</div>';

                    html += '<div style="margin-top:8px">';
                    html += settingEntranceAnimation(settings);
                    html += '</div>';
                    break;
                    
                case 'code':
                    var codeContent = settings.code || '';
                    var codePlacement = settings.placement || 'inline';
                    if (codePlacement === 'body') codePlacement = 'inline'; 

                    html += '<div class="impulse-inline-right" style="margin-bottom:8px">';
                    html += '<label style="font-size:11px">Placement</label>';
                    html += '<div class="impulse-btn-group">';
                    html += '<input type="hidden" name="placement" value="' + codePlacement + '">';
                    html += '<button type="button" class="impulse-btn-option' + (codePlacement === 'head' ? ' active' : '') + '" data-value="head" style="padding:4px 10px;font-size:11px;height:26px">Head</button>';
                    html += '<button type="button" class="impulse-btn-option' + (codePlacement === 'inline' ? ' active' : '') + '" data-value="inline" style="padding:4px 10px;font-size:11px;height:26px">Inline</button>';
                    html += '<button type="button" class="impulse-btn-option' + (codePlacement === 'footer' ? ' active' : '') + '" data-value="footer" style="padding:4px 10px;font-size:11px;height:26px">Footer</button>';
                    html += '</div>';
                    html += '</div>';
                    
                    html += settingTextarea('code', '', codeContent);
                    html += '<p class="impulse-setting-hint">HTML, shortcodes, tracking scripts, embeds</p>';
                    break;

                case 'kinetic': {

                    

                    var _kComp       = settings.composition || 'block-slam';
                    var _kColor      = settings.color || '#ffffff';
                    var _kTag        = (settings.tag || '').toString().toLowerCase();
                    if (['h1','h2','h3'].indexOf(_kTag) === -1) _kTag = '';
                    var _kLoop       = !!(settings.loop && settings.loop != '0' && settings.loop !== false);
                    var _kSpeed      = parseFloat(settings.speed || 1);
                    var _kCustomMode = !!(settings.custom_mode && settings.custom_mode != '0' && settings.custom_mode !== false);
                    var _kCustomLines = [];
                    try {
                        var _kclRaw = settings.custom_lines;
                        if (_kclRaw) {
                            _kCustomLines = (typeof _kclRaw === 'string') ? JSON.parse(_kclRaw) : _kclRaw;
                        }
                    } catch(e) { _kCustomLines = []; }
                    if (!Array.isArray(_kCustomLines)) _kCustomLines = [];
                    var _kText  = settings.text;
                    if (_kText === undefined || _kText === null || _kText === '') {
                        if (settings.raw_text) {
                            _kText = settings.raw_text;
                        } else if (settings.phrases) {
                            try {
                                var _kp = JSON.parse(settings.phrases);
                                if (Array.isArray(_kp)) {
                                    _kText = _kp.map(function(p) { return (p && p.text) || ''; }).filter(Boolean).join('\n');
                                }
                            } catch(e) {}
                        }
                    }
                    _kText = _kText || '';

                    

                    

                    if (_kCustomMode && !_kCustomLines.length && _kText) {
                        var _kSeed = _kText.split('\n').map(function(s){ return s.trim(); }).filter(Boolean);
                        _kSeed.forEach(function(t, i) {
                            var _dm = ['rise','bounce-slide-split','letter-kick-in','drop'][i % 4];
                            _kCustomLines.push({ text: t, motion: _dm, scale: 1.0 });
                        });
                    }

                    var _kCompCatalog = null;
                    var _kMotionGroups = null;
                    try {
                        var _kIfr = document.getElementById('impulse-iframe');
                        if (_kIfr && _kIfr.contentWindow && _kIfr.contentWindow.ImpulseKinetic) {
                            _kCompCatalog  = _kIfr.contentWindow.ImpulseKinetic.compositions;
                            _kMotionGroups = _kIfr.contentWindow.ImpulseKinetic.entryMotionGroups;
                        }
                    } catch(e) {}
                    if (!_kCompCatalog) _kCompCatalog = { 'block-slam': { name: 'Block Slam' } };
                    if (!_kMotionGroups) _kMotionGroups = [{ group: 'Default', motions: [{ value: 'rise', label: 'Rise' }] }];

                    html += '<div class="impulse-section-divider" style="margin-top:0">Mode</div>';

                    
                    var _kCustomLockedFree = window.isProLocked && window.isProLocked();
                    var _kCustomLockA = _kCustomLockedFree ? ' data-pro-locked="1" data-pro-label="Per-Line motions"' : '';
                    var _kCustomLockC = _kCustomLockedFree ? ' impulse-pro-locked' : '';
                    html += '<div class="impulse-btn-group" data-name="custom_mode_toggle" style="display:grid;grid-template-columns:1fr 1fr;gap:3px;margin-bottom:10px">';
                    html += '<button type="button" class="impulse-la-preset-btn' + (!_kCustomMode ? ' active' : '') + '" data-value="0">Composition</button>';
                    html += '<button type="button" class="impulse-la-preset-btn' + (_kCustomMode  ? ' active' : '') + _kCustomLockC + '" data-value="1"' + _kCustomLockA + '>Per-Line</button>';
                    html += '</div>';
                    html += '<input type="hidden" name="custom_mode" value="' + (_kCustomMode ? '1' : '0') + '">';
                    html += '<input type="hidden" name="custom_lines" value="' + escapeHtml(JSON.stringify(_kCustomLines)) + '">';

                    

                    html += '<div class="impulse-section-divider">Tag (SEO)</div>';
                    html += '<div class="impulse-btn-group" data-name="tag" style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px;margin-bottom:4px">';
                    [['', 'None'], ['h1', 'H1'], ['h2', 'H2'], ['h3', 'H3']].forEach(function(opt) {
                        html += '<button type="button" class="impulse-la-preset-btn impulse-kinetic-tag-btn' + (_kTag === opt[0] ? ' active' : '') + '" data-value="' + opt[0] + '">' + opt[1] + '</button>';
                    });

                    html += '<input type="hidden" name="tag" value="' + escapeHtml(_kTag) + '">';
                    html += '</div>';
                    html += '<div style="font-size:10px;color:' + ImpC.dim + ';line-height:1.4;margin-bottom:10px">None: decorative. H1-H3: real heading for SEO (use one H1 per page).</div>';

                    if (!_kCustomMode) {

                        html += '<div class="impulse-section-divider">Text</div>';
                        html += '<textarea name="text" rows="5" class="impulse-settings-input impulse-autosave" placeholder="One line per slot." style="width:100%;font-size:11px;padding:6px 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-family:inherit;resize:vertical;line-height:1.5;box-sizing:border-box;margin-bottom:4px">' + escapeHtml(_kText) + '</textarea>';
                        html += '<div style="font-size:10px;color:' + ImpC.dim + ';line-height:1.4;margin-bottom:10px">Headlines only · 1-4 short lines · 1-4 words each · no paragraphs</div>';

                        

                        

                        
                        html += '<div class="impulse-section-divider">Composition</div>';
                        html += '<div class="impulse-btn-group" data-name="composition" style="display:grid;grid-template-columns:repeat(6,1fr);gap:3px;margin-bottom:6px">';
                        var _kCompNum = 0;
                        Object.keys(_kCompCatalog).forEach(function(key) {
                            _kCompNum++;
                            var entry = _kCompCatalog[key] || {};
                            var name  = entry.name || key;
                            var desc  = entry.description || '';
                            var full  = name + (desc ? ' · ' + desc : '');
                            var pl    = window.isProEffect && window.isProEffect('kineticCompositions', key);
                            var lockA = pl ? ' data-pro-locked="1" data-pro-label="' + escapeHtml(name) + ' composition"' : '';
                            var lockC = pl ? ' impulse-pro-locked' : '';
                            html += '<button type="button" class="impulse-la-preset-btn' + (_kComp === key ? ' active' : '') + lockC + '" data-value="' + escapeHtml(key) + '" data-desc="' + escapeHtml(full) + '" title="' + escapeHtml(name) + '"' + lockA + ' style="padding:0;min-width:0">' + _kCompNum + '</button>';
                        });
                        html += '</div>';
                        html += '<input type="hidden" name="composition" value="' + escapeHtml(_kComp) + '">';
                        var _kCompEntry = _kCompCatalog[_kComp] || {};
                        var _kCompDesc  = (_kCompEntry.name || '') + (_kCompEntry.description ? ' · ' + _kCompEntry.description : '');
                        html += '<div class="impulse-kinetic-comp-desc" style="font-size:10px;color:' + ImpC.dim + ';margin-bottom:10px;line-height:1.4;min-height:14px">' + escapeHtml(_kCompDesc) + '</div>';

                        

                        
                        var _kSceneFx = (['slide', 'sweep', 'brutal', 'arc'].indexOf(_kComp) > -1);
                        if (_kSceneFx) {

                            
                            var _kTier = settings.tier || 'hero';
                            html += '<div class="impulse-section-divider">Hierarchy</div>';
                            html += '<input type="hidden" name="tier" value="' + escapeHtml(_kTier) + '">';
                            html += '<div class="impulse-btn-group" data-name="tier_toggle" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px;margin-bottom:10px">';
                            [['hero','Hero'],['label','Label'],['equal','Equal']].forEach(function(o){
                                html += '<button type="button" class="impulse-la-preset-btn' + (_kTier === o[0] ? ' active' : '') + '" data-value="' + o[0] + '">' + o[1] + '</button>';
                            });
                            html += '</div>';

                            
                        }
                    } else {

                        
                        html += '<input type="hidden" name="composition" value="' + escapeHtml(_kComp) + '">';
                        html += '<input type="hidden" name="text" value="' + escapeHtml(_kText) + '">';

                        

                        var _displayLines = _kCustomLines.slice(0, 4);
                        
                        if (!_displayLines.length) _displayLines.push({ text: '', motion: 'rise' });

                        html += '<div class="impulse-section-divider">Lines</div>';
                        html += '<div class="impulse-kinetic-custom-list" style="margin-bottom:8px">';
                        _displayLines.forEach(function(cl, idx) {
                            var txt    = (cl && cl.text) || '';
                            var motion = (cl && cl.motion) || 'rise';
                            var scale  = (cl && cl.scale != null) ? parseFloat(cl.scale) : 1.0;
                            if (!isFinite(scale) || scale <= 0) scale = 1.0;
                            
                            html += '<div class="impulse-kinetic-custom-row" data-idx="' + idx + '" style="display:flex;flex-direction:column;gap:3px;margin-bottom:6px;padding:5px;background:' + ImpC.surface + ';border:1px solid ' + ImpC.border + ';border-radius:4px">';
                            
                            html += '<input type="text" class="impulse-kinetic-custom-text" data-idx="' + idx + '" placeholder="Line text" value="' + escapeHtml(txt) + '" style="height:26px;font-size:11px;padding:4px 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-family:inherit;box-sizing:border-box;width:100%">';

                            
                            html += '<div style="display:flex;gap:3px;align-items:center">';

                            

                            
                            
                            var _curMoLabel = '';
                            _kMotionGroups.forEach(function(g){ g.motions.forEach(function(m){ if (m.value === motion) _curMoLabel = m.label; }); });
                            if (!_curMoLabel) _curMoLabel = motion;
                            html += '<div class="impulse-kinetic-mo" data-idx="' + idx + '" style="position:relative;flex:1;min-width:0">';
                            html += '<input type="hidden" class="impulse-kinetic-custom-motion" data-idx="' + idx + '" value="' + escapeHtml(motion) + '">';
                            html += '<button type="button" class="impulse-kinetic-mo-trigger" data-idx="' + idx + '" title="Line motion" style="width:100%;height:26px;display:flex;align-items:center;justify-content:space-between;gap:2px;padding:0 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;box-sizing:border-box;overflow:hidden">';
                            html += '<span class="impulse-kinetic-mo-label" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escapeHtml(_curMoLabel) + '</span>';
                            html += '<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" style="opacity:0.55;flex-shrink:0"><path d="M6 9l6 6 6-6"/></svg>';
                            html += '</button>';
                            html += '<div class="impulse-kinetic-mo-menu" style="display:none;position:absolute;top:28px;left:0;min-width:100%;max-height:264px;overflow-y:auto;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;z-index:70;box-shadow:0 4px 14px rgba(0,0,0,0.45)">';

                            
                            
                            _kMotionGroups.forEach(function(g) {
                                g.motions.forEach(function(m) {
                                    var _moAct = (m.value === motion);
                                    html += '<button type="button" class="impulse-kinetic-mo-opt' + (_moAct ? ' active' : '') + '" data-idx="' + idx + '" data-value="' + escapeHtml(m.value) + '" style="display:block;width:100%;height:22px;line-height:22px;background:' + (_moAct ? ImpC.surface : 'transparent') + ';border:none;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;padding:0 8px;text-align:left;white-space:nowrap">' + escapeHtml(m.label) + '</button>';
                                });
                            });
                            html += '</div>';
                            html += '</div>';

                            

                            var _kTgtLine = (cl && (String(cl.target) === 'line' || String(cl.target) === 'whole'));
                            html += '<input type="hidden" class="impulse-kinetic-line-target" data-idx="' + idx + '" value="' + (_kTgtLine ? 'line' : 'word') + '">';
                            html += '<button type="button" class="impulse-kinetic-tgt-toggle impulse-tip-left" data-idx="' + idx + '" data-tip="Word = animate each word; Line = the whole line moves as one" style="flex-shrink:0;width:48px;height:26px;padding:0 6px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;box-sizing:border-box">' + (_kTgtLine ? 'Line' : 'Word') + '</button>';

                            

                            var _scaleVal = (cl && cl.scale != null && parseFloat(cl.scale) > 0) ? parseFloat(cl.scale) : 1;
                            var _sizeSteps = [[0.5,'XS'],[0.7,'S'],[1,'M'],[1.5,'L'],[2,'XL'],[2.8,'XXL']];
                            var _curSizeLab = 'M';
                            _sizeSteps.forEach(function(o){ if (Math.abs(_scaleVal - o[0]) < 0.02) _curSizeLab = o[1]; });
                            html += '<div class="impulse-kinetic-size" data-idx="' + idx + '" style="position:relative;flex-shrink:0;width:62px">';
                            html += '<input type="hidden" class="impulse-kinetic-line-scale" data-idx="' + idx + '" value="' + _scaleVal + '">';
                            html += '<button type="button" class="impulse-kinetic-size-trigger impulse-tip-left" data-tip="Line size — relative; the block auto-fits" data-idx="' + idx + '" style="width:62px;height:26px;display:flex;align-items:center;justify-content:space-between;gap:2px;padding:0 6px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;box-sizing:border-box">';
                            html += '<span class="impulse-kinetic-size-label">' + escapeHtml(_curSizeLab) + '</span>';
                            html += '<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" style="opacity:0.55;flex-shrink:0"><path d="M6 9l6 6 6-6"/></svg>';
                            html += '</button>';
                            html += '<div class="impulse-kinetic-size-menu" style="display:none;position:absolute;top:28px;left:0;width:62px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;z-index:60;box-shadow:0 4px 14px rgba(0,0,0,0.45)">';
                            _sizeSteps.forEach(function(o) {
                                var act = (Math.abs(_scaleVal - o[0]) < 0.02);
                                html += '<button type="button" class="impulse-kinetic-size-opt' + (act ? ' active' : '') + '" data-idx="' + idx + '" data-value="' + o[0] + '" style="display:block;width:100%;height:26px;scroll-snap-align:center;background:' + (act ? ImpC.surface : 'transparent') + ';border:none;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;padding:0;text-align:center">' + o[1] + '</button>';
                            });
                            html += '</div>';
                            html += '</div>';
                            
                            var _lineColor = (cl && cl.color) || '';
                            html += '<span class="impulse-kinetic-cl-color" data-idx="' + idx + '" title="Line color (blank = block color)" style="flex-shrink:0;display:flex">' + settingColorSwatchOnly('cl_color_' + idx, _lineColor) + '</span>';
                            html += '</div>';
                            
                            html += '<div style="display:flex;gap:3px;align-items:center">';
                            var _lf = (cl && cl.font) || '';
                            html += '<select class="impulse-kinetic-custom-font impulse-sel" data-idx="' + idx + '" title="Line font" style="flex:1;min-width:0;height:26px;font-size:11px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-family:inherit;box-sizing:border-box">';
                            _impulseFontList.forEach(function(f) {
                                html += '<option value="' + escapeHtml(f.v) + '"' + (f.v === _lf ? ' selected' : '') + '>' + escapeHtml(f.l) + '</option>';
                            });
                            html += '</select>';

                            
                            var _lw = (cl && cl.weight) ? String(cl.weight) : '';
                            var _wOpts = [['','Weight'],['300','Light'],['400','Reg'],['500','Med'],['700','Bold'],['800','Heavy'],['900','Black']];
                            var _wLabel = 'Weight';
                            _wOpts.forEach(function(w){ if (w[0] === _lw) _wLabel = w[1]; });
                            html += '<div class="impulse-kinetic-wt" data-idx="' + idx + '" style="position:relative;flex-shrink:0;width:84px">';
                            html += '<input type="hidden" class="impulse-kinetic-custom-weight" data-idx="' + idx + '" value="' + escapeHtml(_lw) + '">';
                            html += '<button type="button" class="impulse-kinetic-wt-trigger" data-idx="' + idx + '" title="Line weight" style="width:84px;height:26px;display:flex;align-items:center;justify-content:space-between;gap:2px;padding:0 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;box-sizing:border-box">';
                            html += '<span class="impulse-kinetic-wt-label">' + escapeHtml(_wLabel) + '</span>';
                            html += '<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" style="opacity:0.55;flex-shrink:0"><path d="M6 9l6 6 6-6"/></svg>';
                            html += '</button>';
                            html += '<div class="impulse-kinetic-wt-menu" style="display:none;position:absolute;top:28px;right:0;width:84px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;z-index:60;overflow:hidden;box-shadow:0 4px 14px rgba(0,0,0,0.45)">';
                            _wOpts.forEach(function(w){
                                var act = (w[0] === _lw);
                                html += '<button type="button" class="impulse-kinetic-wt-opt' + (act ? ' active' : '') + '" data-idx="' + idx + '" data-value="' + w[0] + '" style="display:block;width:100%;height:24px;background:' + (act ? ImpC.surface : 'transparent') + ';border:none;color:' + ImpC.text + ';font-size:11px;font-family:inherit;cursor:pointer;padding:0 8px;text-align:left">' + escapeHtml(w[1]) + '</button>';
                            });
                            html += '</div>';   
                            html += '</div>';   

                            

                            var _linePx = (cl && parseFloat(cl.px) > 0) ? parseInt(cl.px, 10) : '';
                            html += '<span class="impulse-numstep" style="position:relative;display:inline-flex;flex-shrink:0;width:54px;height:26px">';
                            html += '<input type="number" class="impulse-kinetic-line-px impulse-numstep-input impulse-tip-left" data-idx="' + idx + '" placeholder="px" data-tip="Exact px — overrides relative size; blank = auto (min 12)" value="' + _linePx + '" min="12" max="800" style="width:54px;height:26px;font-size:11px;padding:0 15px 0 6px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-family:inherit;box-sizing:border-box">';
                            html += '<span class="impulse-numstep-arrows">';
                            html += '<button type="button" class="impulse-numstep-up" tabindex="-1" aria-label="Increase"><svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5"><path d="M5 15l7-7 7 7"/></svg></button>';
                            html += '<button type="button" class="impulse-numstep-down" tabindex="-1" aria-label="Decrease"><svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5"><path d="M5 9l7 7 7-7"/></svg></button>';
                            html += '</span>';
                            html += '</span>';
                            html += '</div>';   
                            html += '</div>';   
                        });
                        html += '</div>';

                        if (_displayLines.length < 4) {
                            html += '<button type="button" class="impulse-kinetic-custom-add" style="display:block;width:100%;height:26px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;cursor:pointer;margin-bottom:10px">+ Add line</button>';
                        }
                    }

                    

                    
                    
                    if (!_kCustomMode) {
                        html += '<div class="impulse-kinetic-solid-color" style="' + (settings.fill === 'gradient' ? 'display:none;' : 'display:flex;') + 'align-items:center;gap:8px;margin-bottom:10px">';
                        html += '<div style="flex-shrink:0">' + settingColorSwatchOnly('color', _kColor) + '</div>';
                        html += '<label style="font-size:11px;color:' + ImpC.muted + '">Color</label>';
                        html += '</div>';
                    }

                        

                        

                        var _kFill      = (settings.fill === 'gradient') ? 'gradient' : 'solid';
                        var _kGradMode  = (settings.grad_mode === 'spin') ? 'spin' : 'travel';
                        var _kGradScope = (settings.grad_scope === 'letter') ? 'letter' : 'line';
                        var _kGradC1    = settings.grad_c1 || '#ff2d55';
                        var _kGradC2    = settings.grad_c2 || '#5e5cff';
                        var _kGradShown = (_kFill === 'gradient');

                        
                        html += '<div style="display:flex;align-items:center;gap:5px;margin-bottom:5px">';
                        html += '<div class="impulse-btn-group" data-name="fill" style="display:flex;gap:5px;flex:1">';
                        [['solid','Solid'],['gradient','Gradient']].forEach(function(o){
                            html += '<button type="button" class="impulse-la-preset-btn' + (_kFill === o[0] ? ' active' : '') + '" data-value="' + o[0] + '" style="flex:1">' + o[1] + '</button>';
                        });
                        html += '<input type="hidden" name="fill" value="' + escapeHtml(_kFill) + '">';
                        html += '</div>';
                        html += '<span class="impulse-kinetic-grad-swatches" style="display:' + (_kGradShown ? 'flex' : 'none') + ';gap:5px;flex-shrink:0">';
                        html += settingColorSwatchOnly('grad_c1', _kGradC1);
                        html += settingColorSwatchOnly('grad_c2', _kGradC2);
                        html += '</span>';
                        html += '</div>';

                        html += '<div class="impulse-kinetic-grad-opts" style="display:' + (_kGradShown ? 'flex' : 'none') + ';align-items:center;gap:16px;margin-bottom:10px">';
                        html += '<div class="impulse-btn-group" data-name="grad_mode" style="display:flex;gap:5px;flex:1">';
                        [['travel','Travel'],['spin','Spin']].forEach(function(o){
                            html += '<button type="button" class="impulse-la-preset-btn' + (_kGradMode === o[0] ? ' active' : '') + '" data-value="' + o[0] + '" style="flex:1">' + o[1] + '</button>';
                        });
                        html += '<input type="hidden" name="grad_mode" value="' + escapeHtml(_kGradMode) + '">';
                        html += '</div>';
                        html += '<div class="impulse-btn-group" data-name="grad_scope" style="display:flex;gap:5px;flex:1">';
                        [['letter','Letter'],['line','Line']].forEach(function(o){
                            html += '<button type="button" class="impulse-la-preset-btn' + (_kGradScope === o[0] ? ' active' : '') + '" data-value="' + o[0] + '" style="flex:1">' + o[1] + '</button>';
                        });
                        html += '<input type="hidden" name="grad_scope" value="' + escapeHtml(_kGradScope) + '">';
                        html += '</div>';
                        html += '</div>';

                    
                    
                    var _kIntensity = parseFloat(settings.intensity);
                    if (!isFinite(_kIntensity) || _kIntensity <= 0) _kIntensity = 1;
                    var _kLineGapUI = parseFloat(settings.line_gap);
                    if (!isFinite(_kLineGapUI)) _kLineGapUI = 0;
                    var _kIsCylinder = (_kComp === 'cylinder');

                    

                    
                    
                    var _kHeightMode = settings.height_mode;
                    if (_kHeightMode !== 'auto' && _kHeightMode !== 'fixed' && _kHeightMode !== 'fit') {
                        var _legFit   = !!(settings.fit_container && settings.fit_container != '0' && settings.fit_container !== false);
                        var _legHAOff = (settings.height_auto === '0' || settings.height_auto === 0);
                        _kHeightMode  = _legFit ? 'fit' : (_legHAOff ? 'fixed' : 'auto');
                    }
                    if (_kIsCylinder && _kHeightMode === 'auto') _kHeightMode = 'fixed';
                    var _kFitOn      = (_kHeightMode === 'fit');
                    var _kAutoHeight = (_kHeightMode === 'auto');
                    html += '<div class="impulse-margin-grid">';
                    html += settingSlider('intensity', 'Intensity', _kIntensity, 0.5, 2, 'x', false, true, 1, false, 0.1);
                    html += settingSlider('speed', 'Speed', _kSpeed, 0.25, 3, 'x', false, true, 1, false, 0.25);
                    if (_kIsCylinder) {

                        

                        var _kCylDia = parseFloat(settings.cyl_diameter);
                        if (!isFinite(_kCylDia) || _kCylDia <= 0) _kCylDia = 70;
                        html += settingSlider('cyl_diameter', 'Diameter', _kCylDia, 40, 110, '%', false, true, 70, false, 2);

                        
                        if (!_kFitOn) {
                            html += settingSliderR('height', 'Height', settings, 400, 120, 900, 'px');
                        }
                    } else {

                        html += settingSlider('line_gap', 'Line gap', _kLineGapUI, -50, 100, '', false, true, 0, false, 5);

                        
                        
                        html += settingSliderR('max_width', 'Max width', settings, 0, 0, 100, '%');

                        
                        
                        if (!_kFitOn && !_kAutoHeight) {
                            html += settingSliderR('height', 'Height', settings, 400, 20, 900, 'px');
                        }
                    }
                    html += '</div>';

                    

                    
                    var _kAlign = getResponsiveValue(settings, 'align', 'center');
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="align" style="display:flex;width:100%;gap:3px;margin-top:8px">';
                    [['left', 'Left'], ['center', 'Center'], ['right', 'Right']].forEach(function(o) {
                        html += '<button type="button" data-value="' + o[0] + '" class="' + (_kAlign === o[0] ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o[1] + '</button>';
                    });
                    html += '<input type="hidden" name="align" value="' + escapeHtml(_kAlign) + '">';
                    html += '</div>';

                    

                    html += '<div style="display:flex;align-items:center;gap:8px;margin-top:8px">';
                    html += '<label style="font-size:11px;color:' + ImpC.muted + ';flex-shrink:0">Height</label>';
                    html += '<div class="impulse-btn-group" data-name="height_mode" style="display:flex;flex:1;gap:3px">';
                    var _kHModes = _kIsCylinder ? [['fixed','Fixed'],['fit','Fit container']] : [['auto','Auto'],['fixed','Fixed'],['fit','Fit container']];
                    _kHModes.forEach(function(o){
                        html += '<button type="button" data-value="' + o[0] + '" class="' + (_kHeightMode === o[0] ? 'active' : '') + '" style="flex:1;height:26px;padding:0 4px;font-size:11px;box-sizing:border-box;white-space:nowrap">' + o[1] + '</button>';
                    });
                    html += '<input type="hidden" name="height_mode" value="' + escapeHtml(_kHeightMode) + '">';
                    html += '</div>';
                    html += '</div>';

                    

                    
                    
                    var _kCycle      = !!(settings.cycle && settings.cycle != '0' && settings.cycle !== false);
                    var _kLeadScreen = (settings.lead_screen !== '0' && settings.lead_screen !== 0 && settings.lead_screen !== false);

                    

                    var _kLabRow = '<div style="display:flex;width:100%;justify-content:space-between;font-size:11px;color:' + ImpC.muted + '">';
                    var _kCbRow  = '<div style="display:flex;width:100%;justify-content:space-between;margin-top:5px">';
                    if (_kCustomMode) {
                        _kLabRow += '<label for="kcb_cycle" style="cursor:pointer;margin:0">Cycle lines</label>';
                        _kCbRow  += '<input type="checkbox" id="kcb_cycle" name="cycle" value="1" class="impulse-autosave"' + (_kCycle ? ' checked' : '') + '>';
                    }
                    _kLabRow += '<label for="kcb_loop" style="cursor:pointer;margin:0">Loop</label>';
                    _kCbRow  += '<input type="checkbox" id="kcb_loop" name="loop" value="1" class="impulse-autosave"' + (_kLoop ? ' checked' : '') + '>';
                    _kLabRow += '<label for="kcb_lead" style="cursor:pointer;margin:0">Lead content</label>';
                    _kCbRow  += '<input type="checkbox" id="kcb_lead" name="lead_screen" value="1" class="impulse-autosave"' + (_kLeadScreen ? ' checked' : '') + '>';
                    _kLabRow += '</div>';
                    _kCbRow  += '</div>';
                    html += '<div style="margin-top:10px">' + _kLabRow + _kCbRow + '</div>';

                    

                    
                    
                    var _kScrollExit = (settings.scroll_exit || 'off');
                    html += '<div style="display:flex;align-items:center;gap:8px;margin-top:8px">';
                    html += '<label style="font-size:11px;color:' + ImpC.muted + ';flex-shrink:0">Scroll exit</label>';
                    html += '<input type="hidden" name="scroll_exit" class="impulse-autosave" value="' + escapeHtml(_kScrollExit) + '">';
                    html += '<div class="impulse-scrollexit-group" style="display:flex;flex:1;gap:3px">';
                    [['off','None'],['spring','Spring'],['fade','Fade']].forEach(function(o){
                        var act = (_kScrollExit === o[0]);
                        html += '<button type="button" class="impulse-scrollexit-btn' + (act ? ' active' : '') + '" data-value="' + o[0] + '" style="flex:1;height:26px;font-size:11px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-family:inherit;cursor:pointer;padding:0">' + o[1] + '</button>';
                    });
                    html += '</div>';
                    html += '</div>';
                    break;
                }

                case 'chart':
                    
                    var _chType = settings.chart_type || 'pie';
                    var _chStyleDefault = _chType === 'pie' ? 'flat' : (_chType === 'line' ? 'plain' : 'plain');
                    html += '<div class="impulse-section-divider" style="margin-top:6px">Chart Type</div>';
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="chart_type" style="margin-top:5px;display:grid;grid-template-columns:1fr 1fr 1fr 1fr 1fr;gap:3px">';
                    html += '<button type="button" class="' + (_chType === 'pie' ? 'active' : '') + '" data-value="pie" style="height:26px;font-size:11px">Pie</button>';
                    html += '<button type="button" class="' + (_chType === 'bar' ? 'active' : '') + '" data-value="bar" style="height:26px;font-size:11px">Bar</button>';
                    html += '<button type="button" class="' + (_chType === 'line' ? 'active' : '') + '" data-value="line" style="height:26px;font-size:11px">Line</button>';
                    html += '<button type="button" class="' + (_chType === 'radial' ? 'active' : '') + '" data-value="radial" style="height:26px;font-size:11px">Radial</button>';
                    html += '<button type="button" class="' + (_chType === 'bars' ? 'active' : '') + '" data-value="bars" style="height:26px;font-size:11px">Bars</button>';
                    html += '<input type="hidden" name="chart_type" value="' + _chType + '">';
                    html += '</div>';

                    var _chStyle = settings.chart_style || _chStyleDefault;
                    if (_chType !== 'radial' && _chType !== 'bars') {
                        html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="chart_style" style="margin-top:6px;display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:3px">';
                        if (_chType === 'pie') {
                            html += '<button type="button" class="' + (_chStyle === 'flat' ? 'active' : '') + '" data-value="flat" style="height:26px;font-size:11px">Flat</button>';
                            html += '<button type="button" class="' + (_chStyle === 'exploded' ? 'active' : '') + '" data-value="exploded" style="height:26px;font-size:11px">Exploded</button>';
                            html += '<button type="button" class="' + (_chStyle === 'tilted_ring' ? 'active' : '') + '" data-value="tilted_ring" style="height:26px;font-size:11px">Tilted</button>';
                            html += '<button type="button" class="' + (_chStyle === 'half' ? 'active' : '') + '" data-value="half" style="height:26px;font-size:11px">Half</button>';
                        } else if (_chType === 'bar') {
                            html += '<button type="button" class="' + (_chStyle === 'plain' ? 'active' : '') + '" data-value="plain" style="height:26px;font-size:11px;grid-column:span 2">Plain</button>';
                            html += '<button type="button" class="' + (_chStyle === 'rounded' ? 'active' : '') + '" data-value="rounded" style="height:26px;font-size:11px;grid-column:span 2">Rounded</button>';
                        } else if (_chType === 'line') {
                            html += '<button type="button" class="' + (_chStyle === 'plain' ? 'active' : '') + '" data-value="plain" style="height:26px;font-size:11px;grid-column:span 2">Line</button>';
                            html += '<button type="button" class="' + (_chStyle === 'filled' ? 'active' : '') + '" data-value="filled" style="height:26px;font-size:11px;grid-column:span 2">Area</button>';
                        }
                        html += '<input type="hidden" name="chart_style" value="' + _chStyle + '">';
                        html += '</div>';
                    }

                    if (_chType === 'bar') {
                        var _chOrient = settings.chart_orientation || 'vertical';
                        html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="chart_orientation" style="margin-top:6px;display:grid;grid-template-columns:1fr 1fr;gap:3px">';
                        html += '<button type="button" class="' + (_chOrient === 'vertical' ? 'active' : '') + '" data-value="vertical" style="height:26px;font-size:11px;box-sizing:border-box">Vertical</button>';
                        html += '<button type="button" class="' + (_chOrient === 'horizontal' ? 'active' : '') + '" data-value="horizontal" style="height:26px;font-size:11px;box-sizing:border-box">Horizontal</button>';
                        html += '<input type="hidden" name="chart_orientation" value="' + _chOrient + '">';
                        html += '</div>';
                    }

                    var _chEntries = settings.chart_entries;
                    if (typeof _chEntries === 'string') { try { _chEntries = JSON.parse(_chEntries); } catch(e) { _chEntries = null; } }
                    if (!Array.isArray(_chEntries) || _chEntries.length === 0) {
                        _chEntries = [
                            { label: 'Category A', value: 30, color: '#9CC3E3' },
                            { label: 'Category B', value: 20, color: '#B8D9B0' },
                            { label: 'Category C', value: 15, color: '#F3B48A' },
                            { label: 'Category D', value: 10, color: '#CDB3D4' }
                        ];
                    }
                    
                    var _chIsRadial = (_chType === 'radial');
                    html += '<div class="impulse-section-divider" style="margin-top:10px">' + (_chIsRadial ? 'Value' : 'Data (max 8)') + '</div>';
                    html += '<div id="impulse-chart-entries-list" data-name="chart_entries" style="display:flex;flex-direction:column;gap:4px;margin-top:5px">';
                    _chEntries.forEach(function(row, i) {
                        
                        var _rowHidden = (_chIsRadial && i > 0);
                        var _rowColor = row.color || '#9CC3E3';
                        html += '<div class="impulse-chart-entry-row" data-index="' + i + '" style="display:' + (_rowHidden ? 'none' : 'flex') + ';gap:4px;align-items:center">';

                        html += '<span class="impulse-chart-entry-drag" style="cursor:' + (_chIsRadial ? 'default' : 'grab') + ';padding:2px;color:#666;display:' + (_chIsRadial ? 'none' : 'inline-flex') + ';align-items:center;flex-shrink:0" title="Drag to reorder"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
                        html += '<input type="text" class="ch-row-label" value="' + escapeHtml(row.label || '') + '" placeholder="Label" style="flex:1 1 auto;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';color:'+ImpC.text+';font-size:11px;padding:0 8px;border-radius:3px;box-sizing:border-box;min-width:0">';
                        html += '<input type="text" inputmode="decimal" autocomplete="off" class="ch-row-value" value="' + (row.value != null ? row.value : 0) + '" placeholder="0" style="width:44px;flex:0 0 44px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';color:'+ImpC.text+';font-size:11px;padding:0 6px;border-radius:3px;box-sizing:border-box;text-align:right">';

                        html += '<div class="impulse-color-setting impulse-color-swatch-only" data-name="chart_entry_color_' + i + '" style="display:block;margin:0;width:26px;height:26px;flex-shrink:0">'
                              + '<div class="impulse-color-row" style="height:26px">'
                              + '<div class="impulse-color-swatch" style="--swatch-color:' + _rowColor + ';width:26px;height:26px;min-width:26px;min-height:26px"></div>'
                              + '<input type="hidden" class="impulse-color-text ch-row-color" value="' + _rowColor + '">'
                              + '</div></div>';
                        html += '<button type="button" class="impulse-chart-entry-del" title="Remove" style="width:26px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="chart_entries" value=\'' + JSON.stringify(_chEntries).replace(/'/g,'&#39;') + '\'>';
                    
                    html += '<button type="button" id="impulse-chart-add-entry" class="instinctor-btn instinctor-btn-sm" style="margin-top:4px;width:100%' + (_chIsRadial ? ';display:none' : '') + '">+ Add Entry</button>';

                    
                    if (!_chIsRadial) {
                        var _chPalettesLocal = {
                            pastel:  ['#9CC3E3','#B8D9B0','#F3B48A','#CDB3D4'],
                            muted:   ['#8897A8','#A69F88','#B8A097','#8E9A8A'],
                            vibrant: ['#3B82F6','#10B981','#F59E0B','#EC4899'],
                            mono:    ['#1D2327','#4A4E53','#737780','#9DA2A9'],
                            earth:   ['#8B6F47','#A89078','#C4A57B','#6B4F3A'],
                            ocean:   ['#4EB1BF','#70C8D9','#1B7A8C','#A9DEE6']
                        };
                        html += '<div class="impulse-section-divider" style="margin-top:10px">Palette</div>';
                        html += '<div id="impulse-chart-palette" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;margin-top:5px">';
                        ['pastel','muted','vibrant','mono','earth','ocean'].forEach(function(key) {
                            var swPal = _chPalettesLocal[key] || [];
                            var sw = swPal.map(function(c) {
                                return '<span style="flex:1;height:10px;border-radius:2px;background:' + c + ';min-width:0"></span>';
                            }).join('');
                            html += '<button type="button" class="impulse-chart-palette-btn" data-palette="' + key + '" title="' + key + '" style="display:flex;gap:2px;padding:5px 6px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;align-items:center;width:100%;box-sizing:border-box">' + sw + '</button>';
                        });
                        html += '</div>';
                    }

                    if (_chType === 'pie') {
                        html += '<div class="impulse-section-divider" style="margin-top:10px">Pie</div>';
                        html += '<div class="impulse-margin-grid" style="margin-top:5px">';
                        html += settingSliderR('chart_inner_radius', 'Inner Radius', settings, 0, 0, 80, '%', true);
                        if (_chStyle === 'tilted_ring') {
                            html += settingSliderR('chart_tilt_sens', 'Tilt Sensitivity', settings, 0, 0, 10, '', true);
                        }
                        html += '</div>';
                    }

                    
                    
                    if (_chType === 'radial') {
                        html += '<div class="impulse-section-divider" style="margin-top:10px">Radial</div>';
                        html += '<div class="impulse-margin-grid" style="margin-top:5px">';
                        html += settingSliderR('chart_ring_diameter', 'Ring Diameter', settings, 70, 0, 90, '%', true);
                        html += settingSliderR('chart_ring_thickness', 'Ring Thickness', settings, 18, 4, 40, 'px', true);

                        html += settingSliderR('chart_tilt_sens', 'Tilt Sensitivity', settings, 0, 0, 10, '', true);
                        html += '</div>';
                    }

                    

                    
                    
                    if (!_chIsRadial && _chType !== 'bars') {
                        var _chLegPos = settings.chart_legend_pos || 'right';
                        html += '<div class="impulse-inline-right" style="margin-top:10px">';
                        html += '<label style="font-size:11px">Legend</label>';
                        html += '<div class="impulse-btn-group" data-name="chart_legend_pos" style="display:flex;gap:3px">';
                        html += '<button type="button" class="' + (_chLegPos === 'right' ? 'active' : '') + '" data-value="right" style="height:26px;font-size:11px;padding:0 10px">Side</button>';
                        html += '<button type="button" class="' + (_chLegPos === 'bottom' ? 'active' : '') + '" data-value="bottom" style="height:26px;font-size:11px;padding:0 10px">Bottom</button>';
                        html += '<button type="button" class="' + (_chLegPos === 'off' ? 'active' : '') + '" data-value="off" style="height:26px;font-size:11px;padding:0 10px">Off</button>';
                        html += '<input type="hidden" name="chart_legend_pos" value="' + _chLegPos + '">';
                        html += '</div></div>';
                    }
                    
                    if (!_chIsRadial) {
                        var _chLabFmt = settings.chart_label_format || 'none';
                        html += '<div class="impulse-inline-right" style="margin-top:5px">';
                        html += '<label style="font-size:11px">Labels</label>';
                        html += '<div class="impulse-btn-group" data-name="chart_label_format" style="display:flex;gap:3px">';
                        html += '<button type="button" class="' + (_chLabFmt === 'none' ? 'active' : '') + '" data-value="none" style="height:26px;font-size:11px;padding:0 10px">None</button>';
                        html += '<button type="button" class="' + (_chLabFmt === 'percent' ? 'active' : '') + '" data-value="percent" style="height:26px;font-size:11px;padding:0 10px">%</button>';
                        html += '<button type="button" class="' + (_chLabFmt === 'value' ? 'active' : '') + '" data-value="value" style="height:26px;font-size:11px;padding:0 10px">Value</button>';
                        html += '<input type="hidden" name="chart_label_format" value="' + _chLabFmt + '">';
                        html += '</div></div>';
                    }

                    

                    
                    var _chVolOn = !!(settings.chart_volume && settings.chart_volume !== '0');
                    var _hideAnimate = (_chType === 'pie') && _chVolOn;
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 12px;margin-top:10px;align-items:center">';
                    if (_hideAnimate) {
                        html += '<span></span>';
                    } else {
                        html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#e0e0e0;justify-self:start">';
                        html +=   '<input type="checkbox" name="chart_animate"' + (settings.chart_animate !== false && settings.chart_animate !== '0' ? ' checked' : '') + '>';
                        html +=   '<span>Animate</span>';
                        html += '</label>';
                    }
                    if (_chType === 'bars' || _chType === 'line') {

                        

                        html += '<span></span>';
                    } else {
                        html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#e0e0e0;justify-self:end">';
                        html +=   '<span>3D</span>';
                        html +=   '<input type="checkbox" name="chart_volume"' + (_chVolOn ? ' checked' : '') + '>';
                        html += '</label>';
                    }
                    html += '</div>';
                    break;

                case 'price_list':
                    
                    var plItems = settings.pl_items || [
                        {title:'Consultation',desc:'',price:'$50',icon:'circle'},
                        {title:'Basic Package',desc:'Includes setup and training',price:'$199',icon:'circle'},
                        {title:'Premium Package',desc:'Full service with priority support',price:'$499',icon:'circle'}
                    ];
                    if (typeof plItems === 'string') { try { plItems = JSON.parse(plItems); } catch(e) { plItems = []; } }
                    
                    html += '<div class="impulse-pl-items">';
                    plItems.forEach(function(item, i) {
                        var plIcon = item.icon || 'circle';
                        var iconHTML = plIcon === 'none' ? '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="#666" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>' : lucideSvg(plIcon, 12);
                        html += '<div class="impulse-pl-item" data-index="' + i + '" data-icon="' + plIcon + '" style="margin-bottom:5px">';
                        
                        html += '<div style="display:flex;gap:5px;align-items:center">';
                        html += '<span class="impulse-pl-drag" style="cursor: default;padding:2px;color:#666"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
                        html += '<button type="button" class="impulse-pl-icon-btn" data-index="' + i + '" style="width:26px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.muted+';flex-shrink:0;box-sizing:border-box;position:relative">' + iconHTML + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span></button>';
                        html += '<input type="text" data-field="title" value="' + escapeHtml(item.title || '') + '" placeholder="Item name" style="flex:1;min-width:0;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                        html += '<input type="text" data-field="price" value="' + escapeHtml(item.price || '') + '" placeholder="$0" style="width:38px;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box;text-align:right">';
                        html += '<button type="button" class="impulse-pl-remove" style="width:26px;flex-shrink:0;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                        
                        html += '<input type="text" data-field="desc" data-index="' + i + '" value="' + escapeHtml(item.desc || '') + '" placeholder="Description (optional)" style="width:100%;height:22px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:10px;color:#888;box-sizing:border-box;margin-top:5px">';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<button type="button" class="impulse-pl-add instinctor-btn" style="width:100%;height:26px;margin-top:10px;font-size:11px">Add Item</button>';
                    html += '<input type="hidden" name="pl_items" value="' + escapeHtml(JSON.stringify(plItems)) + '">';

                    html += '<div class="impulse-section-divider">Connector</div>';
                    var plSep = settings.pl_separator || 'dashed';
                    html += '<div class="impulse-btn-group-rows" style="display:flex;flex-direction:column;gap:3px">';
                    html += '<div class="impulse-btn-group" data-name="pl_separator" data-toggleable="1" style="display:flex;width:100%;gap:3px">';
                    [{v:'dashed',l:'Dashed'},{v:'solid',l:'Line'},{v:'fade',l:'Fade'},{v:'dots',l:'Dots'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (plSep === o.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '</div>';
                    html += '<div class="impulse-btn-group" data-name="pl_separator" data-toggleable="1" style="display:flex;width:100%;gap:3px">';
                    [{v:'wave',l:'Wave'},{v:'zigzag',l:'Zigzag'},{v:'pulse',l:'Pulse'},{v:'shimmer',l:'Shimmer'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (plSep === o.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="pl_separator" value="' + plSep + '">';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;margin-top:12px">';
                    html += '<div><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Icon</label>' + settingColorSwatchOnly('pl_icon_color', settings.pl_icon_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="text-align:center"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Title</label><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('pl_title_color', settings.pl_title_color || ''+ImpC.surface2+'') + '</div></div>';
                    html += '<div style="text-align:right"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Price</label><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('pl_price_color', settings.pl_price_color || ''+ImpC.surface2+'') + '</div></div>';
                    html += '</div>';
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;margin-top:8px">';
                    html += '<div><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Description</label>' + settingColorSwatchOnly('pl_desc_color', settings.pl_desc_color || '#888888') + '</div>';
                    html += '<div style="text-align:center"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Connector</label><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('pl_sep_color', settings.pl_sep_color || '#cccccc') + '</div></div>';
                    html += '<div style="text-align:right"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Divider</label><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('pl_border_color', settings.pl_border_color || ''+ImpC.text+'') + '</div></div>';
                    html += '</div>';

                    var plShowDivider = settings.pl_show_divider !== undefined ? settings.pl_show_divider : '1';
                    html += '<label style="display:flex;align-items:center;gap:6px;margin-top:8px;cursor:pointer;color:'+ImpC.muted+';font-size:11px">';
                    html += '<input type="checkbox" name="pl_show_divider" ' + (plShowDivider === '1' || plShowDivider === 1 || plShowDivider === true ? 'checked' : '') + '>';
                    html += '<span>Show divider between items</span></label>';

                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    html += settingSliderR('pl_icon_size', 'Icon', settings, 18, 10, 32, 'px', true);
                    html += settingSliderR('pl_title_size', 'Title', settings, 16, 12, 28, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('pl_price_size', 'Price', settings, 16, 12, 28, 'px', true);
                    html += settingSliderR('pl_desc_size', 'Description', settings, 13, 10, 20, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('pl_spacing', 'Spacing', settings, 16, 4, 40, 'px', true);
                    html += settingSliderR('section_max_width', 'Max width', settings, 800, 200, 1600, 'px');
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    break;
                
                case 'title':

                    

                    
                    var _legacyStroke = !!(settings.stroke_enabled);
                    var _legacyDepth  = !!(settings.depth_effects)
                                      || !!(settings.depth_of_field)
                                      || !!(settings.depth_shadow)
                                      || (parseInt(settings.line_1_depth)||0) !== 0
                                      || (parseInt(settings.line_1_yrot )||0) !== 0;
                    var dt3dMode = settings.dt_3d_mode || '';
                    if (['flat','outline','depth','outline_depth'].indexOf(dt3dMode) < 0) {
                        if      (_legacyStroke && _legacyDepth) dt3dMode = 'outline_depth';
                        else if (_legacyStroke)                 dt3dMode = 'outline';
                        else if (_legacyDepth)                  dt3dMode = 'depth';
                        else                                    dt3dMode = 'flat';
                    }
                    html += '<input type="hidden" name="dt_3d_mode" value="' + dt3dMode + '">';

                    
                    var _strokeEnabled = (dt3dMode === 'outline' || dt3dMode === 'outline_depth');
                    var _depthOn       = (dt3dMode === 'depth'   || dt3dMode === 'outline_depth');

                    var _hdrCt = settings.la_content_type || 'text';
                    html += '<div class="impulse-btn-group" data-name="la_content_type" style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:8px">';
                    html += '<button type="button" class="' + (_hdrCt === 'text' ? 'active' : '') + '" data-value="text" style="height:26px;font-size:11px">Text</button>';
                    html += '<button type="button" class="' + (_hdrCt === 'image' ? 'active' : '') + '" data-value="image" style="height:26px;font-size:11px">Image</button>';
                    html += '<input type="hidden" name="la_content_type" value="' + _hdrCt + '">';
                    html += '</div>';

                    
                    var _hdrImgSrc = settings.la_image_src || '';
                    var _hdrIsSvg  = _hdrImgSrc && /\.svg(\?|$)/i.test(_hdrImgSrc);
                    var _hdrSvgRaw = _hdrIsSvg ? (settings.la_svg_colors || '') : '';
                    var _hdrSvgMap = {};
                    try { if (_hdrSvgRaw) _hdrSvgMap = JSON.parse(_hdrSvgRaw); } catch(e) {}
                    var _hdrSvgOrig = Object.keys(_hdrSvgMap);
                    html += '<div class="la-image-settings" style="' + (_hdrCt === 'text' ? 'display:none' : '') + ';margin-bottom:8px">';
                    html += '<input type="hidden" name="la_svg_colors" value="' + escapeHtml(settings.la_svg_colors || '') + '">';
                    html += '<input type="hidden" name="la_image_src" value="' + escapeHtml(_hdrImgSrc) + '">';
                    html += '<div class="impulse-setting-row impulse-image-setting" data-name="la_image_src" style="align-items:flex-start">';
                    html += '<label style="padding-top:5px">Image</label>';
                    if (_hdrImgSrc) {
                        html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="la_image_src" style="display:none;height:26px">Select</button>';
                        html += '<div class="impulse-image-preview" style="display:flex;flex-wrap:wrap;align-items:center;gap:4px">';
                        html += '<button type="button" class="impulse-remove-image-btn" data-name="la_image_src" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button>';
                        if (_hdrIsSvg) {
                            if (_hdrSvgOrig.length) {
                                _hdrSvgOrig.forEach(function(orig, i) {
                                    var cur = _hdrSvgMap[orig] || orig;
                                    html += settingColorSwatchOnly('la_svg_color_' + i, cur, orig);
                                    html += '<input type="hidden" name="la_svg_orig_' + i + '" value="' + escapeHtml(orig) + '">';
                                });
                            } else {
                                html += '<span id="impulse-la-svg-pending" data-url="' + escapeHtml(_hdrImgSrc) + '" style="font-size:11px;color:#888">Loading…</span>';
                            }
                        }
                        html += '</div>';
                    } else {
                        html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="la_image_src" style="height:26px">Select</button>';
                    }
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('la_image_width', 'Width', settings, 280, 40, 800, 'px', true);
                    html += '<div></div>';
                    html += '</div>';
                    html += '</div>';

                    
                    html += '<div class="la-text-settings" style="' + (_hdrCt === 'image' ? 'display:none' : '') + '">';

                    
                    var _hdrText   = (getResponsiveValue(settings, 'line_1', '') || '').replace(/"/g,'&quot;');
                    var _hdrWeight = settings.line_1_weight || '700';
                    var _hdrFill   = settings.line_1_fill === 'stroke' ? 'solid' : (settings.line_1_fill || 'solid');

                    

                    

                    

                    var _hdrColor  = settings.line_1_color || '';
                    var _hdrG1     = settings.line_1_grad_1 || '';
                    var _hdrG2     = settings.line_1_grad_2 || '#999999';
                    var _hdrFont   = settings.line_1_font || settings.font_family || '';
                    html += '<div class="impulse-dt-line-block" data-line="1">';

                    

                    

                    html += '<textarea name="line_1" rows="2" placeholder="Title" style="width:100%;min-height:26px;padding:4px 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box;outline:none;resize:vertical;font-family:inherit;line-height:1.4">' + escapeHtml(_hdrText) + '</textarea>';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="line_1_weight" style="margin-top:4px;display:flex;width:100%;gap:3px">';
                    [{v:'300',l:'Light'},{v:'600',l:'Semi'},{v:'800',l:'Extra'},{v:'900',l:'Black'}].forEach(function(w) {
                        var avail = _fontHasWeight(_hdrFont, w.v);
                        html += '<button type="button" class="' + (_hdrWeight === w.v ? 'active' : '') + '" data-value="' + w.v + '" style="flex:1;height:26px;padding:0;font-size:10px;box-sizing:border-box' + (avail ? '' : ';opacity:0.2;pointer-events:none') + '">' + w.l + '</button>';
                    });
                    html += '<input type="hidden" name="line_1_weight" value="' + _hdrWeight + '">';
                    html += '</div>';
                    var _hdrIsGrad = _hdrFill === 'gradient';
                    var _hdrSw1    = _hdrIsGrad ? _hdrG1 : _hdrColor;
                    var _hdrSw2    = _hdrIsGrad ? _hdrG2 : '';
                    html += '<div style="display:flex;align-items:center;gap:4px;margin-top:4px">';
                    html += '<div style="flex-shrink:0;height:26px;overflow:hidden">' + settingColorSwatchOnly('line_1_color', _hdrSw1, 'Fill') + '</div>';
                    html += settingColorSwap('line_1_color', 'line_1_grad_2', 'Swap fill ↔ gradient');
                    html += '<div style="flex-shrink:0;height:26px;overflow:hidden">' + settingColorSwatchOnly('line_1_grad_2', _hdrIsGrad ? _hdrSw2 : (_hdrSw2 || '#999999'), 'Gradient') + '</div>';
                    html += '<div style="flex-shrink:0;height:26px;overflow:hidden;' + (_strokeEnabled ? '' : 'opacity:0.35;pointer-events:none') + '">' + settingColorSwatchOnly('line_1_stroke', settings.line_1_stroke || '', 'Outline') + '</div>';

                    
                    html += '<div style="flex-shrink:0;height:26px;overflow:hidden;' + (_strokeEnabled ? '' : 'opacity:0.35;pointer-events:none') + '">' + settingColorSwatchOnly('line_1_stroke_2', settings.line_1_stroke_2 || '', 'Outline 2') + '</div>';
                    html += '<input type="hidden" name="line_1_fill" value="' + _hdrFill + '">';
                    html += '<input type="hidden" name="line_1_grad_1" value="' + _hdrSw1 + '">';
                    var _hdrFontLabel = 'Default';
                    _impulseFontList.forEach(function(f) { if (f.v === _hdrFont) _hdrFontLabel = f.l; });
                    html += '<div class="impulse-font-picker impulse-dt-font-picker" style="flex:1;min-width:0;position:relative">';
                    html += '<div class="impulse-font-trigger" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.muted+';font-size:10px;padding:0 6px;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;justify-content:space-between;overflow:hidden;' + (_hdrFont ? 'font-family:' + _hdrFont : '') + '">';
                    html += '<span class="impulse-font-trigger-label" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + _hdrFontLabel + '</span>';
                    html += '<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="#666" stroke-width="2" style="flex-shrink:0"><path d="m6 9 6 6 6-6"/></svg>';
                    html += '</div><div class="impulse-font-options" style="display:none">';
                    _impulseFontList.forEach(function(f) {
                        html += '<div class="impulse-font-option' + (f.v === _hdrFont ? ' active' : '') + '" data-value="' + f.v.replace(/"/g, '&quot;') + '" style="' + (f.v ? 'font-family:' + f.v : '') + '">' + f.l + '</div>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="line_1_font" value="' + (_hdrFont || '') + '">';
                    html += '</div></div></div>';

                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="tag" style="margin-top:10px;display:flex;width:100%;gap:3px">';
                    ['h1','h2','h3','h4','h5','h6','p','div'].forEach(function(t) {
                        html += '<button type="button" class="' + ((settings.tag || 'h2') === t ? 'active' : '') + '" data-value="' + t + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + t.toUpperCase() + '</button>';
                    });
                    html += '<input type="hidden" name="tag" value="' + (settings.tag || 'h2') + '">';

                    

                    

                    var _hdrAlignVal = (typeof getResponsiveValue === 'function')
                        ? getResponsiveValue(settings, 'align', 'center')
                        : (settings.align || 'center');
                    html += '</div>';
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="align" style="margin-top:3px;display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + (_hdrAlignVal === 'left' ? 'active' : '') + '" data-value="left" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + (_hdrAlignVal === 'center' ? 'active' : '') + '" data-value="center" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="10" x2="6" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="18" y1="18" x2="6" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + (_hdrAlignVal === 'right' ? 'active' : '') + '" data-value="right" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="21" y1="10" x2="7" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="7" y2="18"/></svg></button>';
                    html += '<input type="hidden" name="align" value="' + _hdrAlignVal + '">';
                    html += '</div>';

                    

                    var _dtAnyDepth    = _depthOn || (parseInt(settings.line_1_depth)||0) !== 0 || (parseInt(settings.line_1_yrot)||0) !== 0;
                    var _hdrPresetLock = !!(settings.la_preset);

                    var _modeBtns = [
                        {v: 'flat',          l: 'Flat'},
                        {v: 'outline',       l: 'Outline'},
                        {v: 'depth',         l: 'Depth'},
                        {v: 'outline_depth', l: 'Outline+Depth'}
                    ];

                    

                    

                    

                    
                    html += '<div class="impulse-btn-group impulse-hdr-mode" data-name="dt_3d_mode" style="display:grid;grid-template-columns:1fr 1fr 1fr 1.6fr;gap:3px;margin-top:8px;margin-bottom:6px;' + (_hdrPresetLock ? 'opacity:0.35' : '') + '">';
                    _modeBtns.forEach(function(m) {
                        html += '<button type="button" class="' + (dt3dMode === m.v ? 'active' : '') + '" data-value="' + m.v + '" style="height:26px;padding:0;font-size:10px;box-sizing:border-box">' + m.l + '</button>';
                    });
                    html += '</div>';

                    

                    html += '<input type="hidden" name="stroke_bevel" value="' + (_strokeEnabled ? '1' : '') + '">';

                    
                    html += '<input type="hidden" name="depth_effects"  value="' + (_depthOn       ? '1' : '') + '">';
                    html += '<input type="hidden" name="stroke_enabled" value="' + (_strokeEnabled ? '1' : '') + '">';

                    

                    

                    

                    var _hdrPresetActive = !!(settings.la_preset);
                    var _isFlat = (dt3dMode === 'flat');
                    var _showSliderBlock = !_isFlat || _hdrPresetActive;

                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('line_1_size', 'Size', settings, 48, 16, 200, 'px', true);
                    html += settingSliderR('line_1_grad_angle', 'Gradient Angle', settings, 135, 0, 180, '°', false);
                    html += settingSliderR('letter_spacing', 'Letter Spacing', settings, 0, -5, 30, 'px', true);
                    html += settingSliderR('margin_bottom', 'Gap Below', settings, 0, -200, 200, 'px', true);

                    

                    

                    

                    
                    
                    if (_hdrPresetActive) {
                        html += settingSliderR('mouse_sens', 'Sensitivity', settings, 5, 0, 50, '', true);
                    }
                    html += '</div>';

                    html += '<div style="margin-top:10px">';

                    
                    html += '<input type="hidden" name="depth_of_field" value="' + (_depthOn ? '1' : '') + '">';
                    html += '<input type="hidden" name="depth_shadow" value="' + (_depthOn ? '1' : '') + '">';
                    html += '<input type="hidden" name="dt_3d_mouse" value="1">';

                    

                    

                    

                    
                    html += '<div class="impulse-dt-depth-sliders" style="display:' + (_showSliderBlock && !_hdrPresetActive ? 'block' : 'none') + '">';
                    html += '<div class="impulse-margin-grid">';

                    
                    
                    if (_depthOn) {
                        html += settingSliderR('line_1_depth',         'Depth',       settings, 0,   -150, 150,  'px', true);
                        html += settingSliderR('line_1_yrot',          'Rotation',    settings, 0,   -30,  30,   '°',  true);
                        html += settingSliderR('perspective',          'Perspective', settings, 800,  200, 2000, 'px', true, 'Camera distance. Lower = dramatic depth, higher = flat/subtle');
                        html += '<div class="impulse-dt-dof-settings">'        + settingSliderR('dof_intensity',        'Blur',      settings, 5, 1,  10,  '',  true) + '</div>';

                        

                        

                        if (_strokeEnabled) {
                            html += '<div class="impulse-dt-stroke-controls">' + settingSliderR('layer_gap', 'Outline Depth', settings, 0, 0, 600, 'px', true) + '</div>';
                        }
                    }
                    
                    if (_strokeEnabled) {
                        html += '<div class="impulse-dt-stroke-controls">' + settingSliderR('stroke_width',         'Outline Thickness', settings, 1, 1, 10, 'px', true) + '</div>';
                        html += '<div class="impulse-dt-stroke-controls">' + settingSliderR('stroke_rotate_speed',  'Outline Spin',      settings, 0, 0, 10, '',   true) + '</div>';
                    }

                    

                    html += settingSliderR('mouse_sens',  'Sensitivity', settings, 5, 0, 50, '', true);
                    html += settingSliderR('orbit_speed', 'Orbit Speed', settings, 5, 0, 50, '', true);

                    
                    
                    var _autoTilt = !!(settings.auto_tilt && settings.auto_tilt != '0' && settings.auto_tilt !== false);
                    html += '<label style="grid-column:1/-1;display:flex;align-items:center;gap:8px;margin-top:4px;cursor:pointer;font-size:11px;color:' + ImpC.text + '">'
                          +   '<input type="checkbox" name="auto_tilt" value="1"' + (_autoTilt ? ' checked' : '') + '>'
                          +   '<span>Auto-tilt (idle sway)</span>'
                          + '</label>';

                    
                    
                    if (_strokeEnabled) {
                        var _spinMode = (settings.stroke_spin_mode === 'pulse') ? 'pulse' : 'sweep';
                        html += '<div class="impulse-dt-stroke-controls" style="grid-column:1/-1">';
                        html += '<label style="font-size:11px;color:#888;display:block;margin-bottom:4px">Spin Style</label>';
                        html += '<div class="impulse-btn-group impulse-stroke-spin-mode" data-name="stroke_spin_mode" style="display:grid;grid-template-columns:1fr 1fr;gap:3px">';
                        html += '<button type="button" class="' + (_spinMode === 'sweep' ? 'active' : '') + '" data-value="sweep" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">Sweep</button>';
                        html += '<button type="button" class="' + (_spinMode === 'pulse' ? 'active' : '') + '" data-value="pulse" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">Pulse</button>';
                        html += '</div>';
                        html += '<input type="hidden" name="stroke_spin_mode" value="' + _spinMode + '">';
                        html += '</div>';
                    }
                    html += '</div>';
                    html += '</div>';

                    html += '</div>';

                    
                    html += '<div class="impulse-section-divider" style="margin-top:10px">Animation</div>';
                    var _hdrPreset = settings.la_preset || '';
                    var _hdrAnimPresets = [
                        {id:'', l:'None'},
                        {id:'build_columns', l:'Columns'},{id:'build_glitch', l:'Glitch'},{id:'build_decode', l:'Decode'},
                        {id:'build_slots', l:'Slots'},
                        {id:'build_streaks', l:'Streaks'},{id:'build_dissolve', l:'Dissolve'},{id:'build_emerge', l:'Emerge'},
                        {id:'build_zslices', l:'Layers'},{id:'build_converge', l:'Converge'},{id:'mask_iris', l:'Iris'},
                        {id:'voronoi_pop', l:'Cells'},
                        {id:'warp_pinch', l:'Pinch'},
                        {id:'dof_rack', l:'Focus'},{id:'dof_tilt', l:'Tilt'},
                        {id:'noise_elastic', l:'Elastic'},
                        {id:'fx_noise', l:'Noise'},{id:'fx_ripple', l:'Ripple'},{id:'fx_liquid', l:'Liquid'},
                        {id:'fx_shatter', l:'Shatter'},{id:'fx_static', l:'Static'},{id:'fx_melt', l:'Melt'},
                        {id:'fx_glass', l:'Glass'},{id:'fx_wave', l:'Wave'},{id:'fx_smoke', l:'Smoke'},
                        {id:'fx_storm', l:'Storm'},{id:'fx_warp', l:'Warp'},
                        {id:'3d_depth_in', l:'Depth'},
                        {id:'3d_zoom_out', l:'Zoom Out'},{id:'3d_flip_x', l:'Flip X'},{id:'3d_spin_in', l:'Spin'},
                        {id:'3d_swing', l:'Swing'},{id:'3d_unfold', l:'Unfold'},{id:'3d_curtain', l:'Curtain'},
                        {id:'3d_bounce', l:'Bounce'},{id:'3d_rain', l:'Rain'},{id:'3d_stagger_h', l:'Rows'},
                        {id:'3d_explode_in', l:'Explode'},{id:'3d_crystal', l:'Crystal'},
                        {id:'3d_unfurl', l:'Unfurl'},{id:'3d_lightfield', l:'Light Field'},
                        {id:'neon_ignite', l:'Neon'}
                    ];

                    

                    html += '<div class="impulse-btn-group" data-name="la_preset" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px;margin-top:4px">';
                    _hdrAnimPresets.forEach(function(p) {
                        if (!p.id) return; 
                        var pl = window.isProEffect && window.isProEffect('headlineAnims', p.id);
                        var lockA = pl ? ' data-pro-locked="1" data-pro-label="' + p.l + ' animation"' : '';
                        var lockC = pl ? ' impulse-pro-locked' : '';
                        html += '<button type="button" class="impulse-la-preset-btn' + (_hdrPreset === p.id ? ' active' : '') + lockC + '" data-value="' + p.id + '" style="height:26px;padding:0;font-size:10px;box-sizing:border-box"' + lockA + '>' + p.l + '</button>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="la_preset" value="' + _hdrPreset + '">';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSlider('la_duration', 'Duration', (function(){var v=parseFloat(getResponsiveValue(settings,'la_duration',1.2));return v>10?Math.round(v/100)/10:v||1.2;})(), 0.2, 5, 's', false, true, 1.2, false, 0.1);
                    html += settingSlider('la_delay', 'Delay', (function(){var v=parseFloat(getResponsiveValue(settings,'la_delay',0));return v>10?Math.round(v/100)/10:v;})(), 0, 5, 's', false, true, 0, false, 0.1);
                    html += '</div>';

                    

                    

                    break;

                case 'unfold':
                    
                    var itemsData = settings.items || [
                        {title: 'Title 1', content: 'Description 1'},
                        {title: 'Title 2', content: 'Description 2'},
                        {title: 'Title 3', content: 'Description 3'}
                    ];
                    if (typeof itemsData === 'string') {
                        try { itemsData = JSON.parse(itemsData); } catch(e) { itemsData = []; }
                    }

                    html += '<div class="impulse-unfold-editor">';
                    itemsData.forEach(function(item, i) {
                        html += '<div class="impulse-unfold-item-edit" data-index="' + i + '" style="margin-top:' + (i > 0 ? '3' : '0') + 'px">';
                        html += '<div class="impulse-acc-item-header" style="display:flex;gap:3px;align-items:center">';
                        html += '<span class="impulse-unfold-drag" style="cursor: default;color:'+ImpC.dim+';display:flex;align-items:center;flex-shrink:0"><svg width="8" height="14" viewBox="0 0 8 14" fill="currentColor"><circle cx="2" cy="2" r="1.2"/><circle cx="6" cy="2" r="1.2"/><circle cx="2" cy="7" r="1.2"/><circle cx="6" cy="7" r="1.2"/><circle cx="2" cy="12" r="1.2"/><circle cx="6" cy="12" r="1.2"/></svg></span>';
                        html += '<input type="text" class="impulse-unfold-title" value="' + (item.title || '').replace(/"/g, '&quot;') + '" placeholder="Item ' + (i+1) + '" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box;outline:none;min-width:0">';
                        html += '<button type="button" class="impulse-acc-expand-btn" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Edit content"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><polyline points="6 9 12 15 18 9"/></svg></button>';
                        html += '<button type="button" class="impulse-remove-unfold-item" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                        html += '<textarea class="impulse-unfold-content" data-index="' + i + '" placeholder="Back side content..." style="display:none;width:100%;min-height:36px;padding:4px 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';resize:vertical;box-sizing:border-box;margin-top:3px;line-height:1.4;outline:none">' + (item.content || '').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<button type="button" class="impulse-add-unfold-item" style="width:100%;margin-top:3px;height:26px;padding:0 12px;background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;box-sizing:border-box">Add Item</button>';
                    html += '<input type="hidden" name="items" value=\'' + JSON.stringify(itemsData).replace(/'/g, '&#39;') + '\'>';

                    var accAnimStyle = settings.anim_style || 'spotlight';
                    var isScrollMode = (accAnimStyle === 'rolodex');
                    var isNewMode   = (accAnimStyle === 'spotlight');
                    var isTilesMode = (accAnimStyle === 'tiles');
                    var isClickMode = false;

                    

                    
                    html += '<div class="impulse-btn-group-rows impulse-acc-anim-rows">';
                    html += '<input type="hidden" name="anim_style" value="' + accAnimStyle + '">';
                    html += '<div class="impulse-btn-group impulse-acc-anim-btn" style="margin-top:3px;display:flex;width:100%;gap:3px">';
                    [{v:'spotlight',l:'Focus'},{v:'rolodex',l:'Stack'},{v:'tiles',l:'Tiles'},{v:'reveal',l:'Reveal'}].forEach(function(a) {
                        html += '<button type="button" class="' + (accAnimStyle === a.v ? 'active' : '') + '" data-value="' + a.v + '" style="flex:1;height:26px;padding:0;font-size:10px;box-sizing:border-box">' + a.l + '</button>';
                    });
                    html += '</div>';
                    html += '</div>';

                    
                    
                    if (accAnimStyle === 'reveal') {
                        var _rvCols = parseInt(settings.reveal_cols) || 1;
                        html += '<div class="impulse-inline-right" style="margin-top:8px">';
                        html += '<label style="font-size:11px">Columns</label>';
                        html += '<div class="impulse-btn-group" data-name="reveal_cols" style="display:flex;gap:3px">';
                        ['1', '2'].forEach(function(v) {
                            html += '<button type="button" class="' + (_rvCols == v ? 'active' : '') + '" data-value="' + v + '" style="height:26px;font-size:11px;padding:0 16px">' + v + '</button>';
                        });
                        html += '<input type="hidden" name="reveal_cols" value="' + _rvCols + '">';
                        html += '</div></div>';
                    }

                    if (isNewMode) {
                        
                        var accTitleColor   = settings.header_color   || ''+ImpC.surface2+'';
                        var accContentBg    = settings.content_bg     || '#ffffff';
                        var accContentColor = settings.content_color  || '#555555';
                        var accAccent       = settings.accent_color   || ''+ImpC.surface2+'';
                        var accBorder       = settings.border_color   || ''+ImpC.text+'';
                        html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px 12px;margin-top:10px">';
                        html += '<div>' + settingColorSwatch('header_color', 'Title', accTitleColor) + '</div>';
                        html += '<div style="text-align:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Content</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('content_color', accContentColor) + '</div></div>';
                        var accSpotBg = settings.spot_bg || '#888888';
                        html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Background</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('spot_bg', accSpotBg) + '</div></div>';
                        html += '<div>' + settingColorSwatch('accent_color', 'Accent', accAccent) + '</div>';
                        html += '<div style="text-align:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Border</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('border_color', accBorder) + '</div></div>';
                        html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Text Area</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('content_bg', accContentBg) + '</div></div>';
                        html += '</div>';
                        
                        html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                        html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 20, 'px', true);
                        html += settingSliderR('blur_intensity', 'Dim Blur', settings, 1, 0, 4, 'px', true);
                        html += '</div>';

                    } else if (isTilesMode) {
                        html += '<div style="margin-top:3px" class="impulse-tiles-panel">';
                        
                        var tExpandVal = settings.tiles_expand || 'flip';
                        html += '<div class="impulse-btn-group" data-name="tiles_expand" style="display:flex;width:100%;gap:3px;margin-bottom:3px">';
                        [{v:'flip',l:'Flip'},{v:'slide',l:'Slide'},{v:'fade',l:'Fade'},{v:'push',l:'Push'}].forEach(function(o) {
                            html += '<button type="button" data-value="' + o.v + '"' + (tExpandVal === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:10px;box-sizing:border-box">' + o.l + '</button>';
                        });
                        html += '<input type="hidden" name="tiles_expand" value="' + tExpandVal + '">';
                        html += '</div>';

                        
                        
                        var _tcDev = window.impulseDevice || 'desktop';
                        var _tcVal;
                        if (_tcDev === 'mobile' && (settings.tiles_cols_mobile === undefined || settings.tiles_cols_mobile === '' || settings.tiles_cols_mobile === null)) {
                            _tcVal = '1';
                        } else {
                            _tcVal = String(getResponsiveValue(settings, 'tiles_cols', '3'));
                        }
                        html += '<div class="impulse-setting-row" data-responsive="true"><label>Columns</label><div class="impulse-btn-group" data-name="tiles_cols">';
                        ['1','2','3','4'].forEach(function(v) {
                            html += '<button type="button" data-value="' + v + '"' + (_tcVal === v ? ' class="active"' : '') + '>' + v + '</button>';
                        });
                        html += '<input type="hidden" name="tiles_cols" value="' + _tcVal + '"></div></div>';
                        
                        html += settingCheckbox('tiles_number', 'Numbers', settings.tiles_number !== false);
                        
                        var tTitleColor = settings.header_color || ''+ImpC.surface2+'';
                        var tContentColor = settings.content_color || '#555555';
                        var tCardBg = settings.content_bg || '#ffffff';
                        var tAccent = settings.accent_color || ''+ImpC.surface2+'';
                        var tBorder = settings.border_color || ''+ImpC.text+'';
                        html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px 12px;margin-top:3px">';
                        html += '<div>' + settingColorSwatch('header_color', 'Title', tTitleColor) + '</div>';
                        html += '<div style="text-align:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Content</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('content_color', tContentColor) + '</div></div>';
                        html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Card</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('content_bg', tCardBg) + '</div></div>';
                        html += '<div>' + settingColorSwatch('accent_color', 'Accent', tAccent) + '</div>';
                        html += '<div></div>';
                        html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Border</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('border_color', tBorder) + '</div></div>';
                        html += '</div>';
                        
                        html += '<div class="impulse-margin-grid" style="margin-top:3px">';
                        html += settingSliderR('card_height', 'Card Height', settings, 180, 80, 400, 'px', true);
                        html += settingSliderR('gap', 'Gap', settings, 16, 0, 40, 'px', true);
                        html += settingSliderR('border_radius', 'Radius', settings, 8, 0, 24, 'px', true);
                        html += settingSliderR('title_size', 'Title Size', settings, 15, 10, 28, 'px', true);
                        html += settingSliderR('content_size', 'Content Size', settings, 14, 10, 24, 'px', true);
                        html += settingSliderR('number_size', 'Number Size', settings, 11, 8, 24, 'px', true);
                        html += settingSliderR('acc_width', 'Width', settings, 100, 30, 100, '%', true);
                        html += '<div></div>';
                        html += '</div>';

                        
                        (function() {
                            var _aic = {
                                left:  '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg>',
                                center:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="10" x2="6" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="18" y1="18" x2="6" y2="18"/></svg>',
                                right: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="21" y1="10" x2="7" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="7" y2="18"/></svg>'
                            };
                            function _alignGrp(name, cur, label) {
                                var h = '<div style="font-size:11px;color:#888;margin:8px 0 4px">' + label + '</div>';
                                h += '<div class="impulse-btn-group impulse-btn-group-full" data-name="' + name + '" style="display:flex;width:100%;gap:3px">';
                                ['left','center','right'].forEach(function(v) {
                                    h += '<button type="button" class="' + (cur === v ? 'active' : '') + '" data-value="' + v + '" title="' + v + '" style="flex:1;height:26px;box-sizing:border-box">' + _aic[v] + '</button>';
                                });
                                h += '<input type="hidden" name="' + name + '" value="' + cur + '"></div>';
                                return h;
                            }
                            var _aA = settings.tiles_align_a || settings.acc_align || 'center';
                            var _aB = settings.tiles_align_b || settings.acc_align || 'center';
                            html += _alignGrp('tiles_align_a', _aA, 'Text Side A');
                            html += _alignGrp('tiles_align_b', _aB, 'Text Side B');
                        })();
                        html += '</div>';

                    } else {
                        html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px 12px;margin-top:10px">';
                        html += '<div>' + settingColorSwatch('header_color', 'Title', settings.header_color || ''+ImpC.surface2+'') + '</div>';
                        html += '<div></div>';
                        if (isScrollMode) {
                            
                            html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Card</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('content_bg', settings.content_bg || '#ffffff') + '</div></div>';
                            html += '<div>' + settingColorSwatch('border_color', 'Border', settings.border_color || ''+ImpC.text+'') + '</div>';
                            html += '<div></div>';
                            html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Content</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('content_color', settings.content_color || '#666666') + '</div></div>';
                        } else {

                            
                            html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Content</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('content_color', settings.content_color || '#666666') + '</div></div>';
                            html += '<div>' + settingColorSwatch('border_color', 'Border', settings.border_color || ''+ImpC.text+'') + '</div>';
                        }
                        html += '</div>';

                        
                    }
                    
                    html += '<input type="hidden" name="unfold_icon" value="' + (settings.unfold_icon || 'chevron-down') + '">';
                    
                    if (!isTilesMode) {
                        html += '<div class="impulse-margin-grid" style="margin-top:10px">';

                        
                        if (isScrollMode) {
                            
                            html += settingSliderR('card_height', 'Height', settings, 200, 100, 500, 'px', true);
                            html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 20, 'px', true);
                        } else {

                            
                            html += settingSliderR('row_padding', 'Item Height', settings, 11, 0, 40, 'px', true);
                        }
                        html += settingSliderR('title_size', 'Title Size', settings, 15, 10, 28, 'px', true);
                        html += settingSliderR('content_size', 'Content Size', settings, 14, 10, 24, 'px', true);
                        if (isScrollMode) {
                            html += settingSliderR('number_size', 'Number Size', settings, 11, 8, 24, 'px', true);
                        }
                        html += settingSliderR('acc_width', 'Width', settings, 100, 30, 100, '%', true);
                        html += '</div>';
                    }

                    

                    if (!isTilesMode) {
                    var _unfAlign = settings.acc_align || 'center';
                    html += '<div style="font-size:11px;color:#888;margin:10px 0 4px">Align</div>';
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="acc_align" style="display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + (_unfAlign === 'left' ? 'active' : '') + '" data-value="left" title="Left" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + (_unfAlign === 'center' ? 'active' : '') + '" data-value="center" title="Center" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="10" x2="6" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="18" y1="18" x2="6" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + (_unfAlign === 'right' ? 'active' : '') + '" data-value="right" title="Right" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="21" y1="10" x2="7" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="7" y2="18"/></svg></button>';
                    html += '<input type="hidden" name="acc_align" value="' + _unfAlign + '">';
                    html += '</div>';
                    } 
                    html += settingEntranceAnimation(settings);
                    break;

                case 'table':

                    var ilCols = parseInt(settings.columns) || 1;
                    if (ilCols < 1) ilCols = 1; if (ilCols > 8) ilCols = 8;
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="columns" style="display:grid;grid-template-columns:repeat(8,1fr);gap:3px">';
                    for (var _c = 1; _c <= 8; _c++) {
                        html += '<button type="button" data-value="' + _c + '" class="' + (ilCols === _c ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">' + _c + '</button>';
                    }
                    html += '<input type="hidden" name="columns" value="' + ilCols + '">';
                    html += '</div>';

                    
                    var _ilShowIcons = settings.show_icons === undefined ? true : (settings.show_icons && settings.show_icons !== '0');
                    var _ilZebra     = settings.zebra_stripes && settings.zebra_stripes !== '0';
                    var _ilShowHeader = settings.show_header === undefined ? true : (settings.show_header && settings.show_header !== '0');
                    var _ilDataAlign = settings.data_align || 'right';

                    

                    
                    var _cbRowL = 'display:flex;align-items:center;align-self:flex-start';
                    var _cbRowC = 'display:flex;align-items:center;align-self:center';
                    var _cbRowR = 'display:flex;align-items:center;align-self:flex-end';
                    if (ilCols >= 2) {
                        html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;margin-top:10px;margin-bottom:6px">';
                        
                        html += '<div style="display:flex;flex-direction:column;align-items:flex-start;gap:4px">';
                        html +=   '<span style="font-size:11px;color:#888">Show Icons</span>';
                        html +=   '<div style="' + _cbRowL + '"><input type="checkbox" name="show_icons"' + (_ilShowIcons ? ' checked' : '') + ' style="margin:0"></div>';
                        html += '</div>';
                        
                        html += '<div style="display:flex;flex-direction:column;align-items:center;gap:4px">';
                        html +=   '<span style="font-size:11px;color:#888">Header</span>';
                        html +=   '<div style="' + _cbRowC + '"><input type="checkbox" name="show_header"' + (_ilShowHeader ? ' checked' : '') + ' style="margin:0"></div>';
                        html += '</div>';
                        
                        html += '<div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px">';
                        html +=   '<span style="font-size:11px;color:#888">Zebra</span>';
                        html +=   '<div style="' + _cbRowR + '"><input type="checkbox" name="zebra_stripes"' + (_ilZebra ? ' checked' : '') + ' style="margin:0"></div>';
                        html += '</div>';
                        html += '</div>';
                    } else {

                        html += '<div style="display:grid;grid-template-columns:1fr 1fr;margin-top:10px;margin-bottom:6px">';
                        html += '<div style="display:flex;flex-direction:column;align-items:flex-start;gap:4px">';
                        html +=   '<span style="font-size:11px;color:#888">Show Icons</span>';
                        html +=   '<div style="' + _cbRowL + '"><input type="checkbox" name="show_icons"' + (_ilShowIcons ? ' checked' : '') + ' style="margin:0"></div>';
                        html += '</div>';
                        html += '<div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px">';
                        html +=   '<span style="font-size:11px;color:#888">Zebra</span>';
                        html +=   '<div style="' + _cbRowR + '"><input type="checkbox" name="zebra_stripes"' + (_ilZebra ? ' checked' : '') + ' style="margin:0"></div>';
                        html += '</div>';
                        html += '</div>';
                    }
                    
                    if (ilCols >= 2) {
                        html += '<div class="impulse-inline-right" style="margin-top:8px">';
                        html += '<label style="font-size:11px">Data Align</label>';
                        html += '<div class="impulse-btn-group" data-name="data_align" style="display:flex;gap:3px">';
                        html += '<button type="button" class="' + (_ilDataAlign === 'left' ? 'active' : '') + '" data-value="left" style="height:26px;font-size:11px;padding:0 10px">Left</button>';
                        html += '<button type="button" class="' + (_ilDataAlign === 'center' ? 'active' : '') + '" data-value="center" style="height:26px;font-size:11px;padding:0 10px">Center</button>';
                        html += '<button type="button" class="' + (_ilDataAlign === 'right' ? 'active' : '') + '" data-value="right" style="height:26px;font-size:11px;padding:0 10px">Right</button>';
                        html += '<input type="hidden" name="data_align" value="' + _ilDataAlign + '">';
                        html += '</div></div>';
                    }

                    
                    if (ilCols >= 2) {
                        var _ilHlCol = parseInt(settings.highlight_col) || 0;
                        if (_ilHlCol < 0 || _ilHlCol > ilCols) _ilHlCol = 0;
                        var _ilHlBg = settings.highlight_bg || '#E7EEDB';
                        html += '<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:10px;margin-bottom:6px">';
                        html += '<label style="font-size:11px;color:#888">Highlight Col</label>';
                        html += settingColorSwatchOnly('highlight_bg', _ilHlBg);
                        html += '</div>';
                        html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="highlight_col" style="display:grid;grid-template-columns:repeat(' + (ilCols + 1) + ',1fr);gap:3px;margin-bottom:4px">';
                        html += '<button type="button" data-value="0" class="' + (_ilHlCol === 0 ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">Off</button>';
                        for (var _hc = 1; _hc <= ilCols; _hc++) {
                            html += '<button type="button" data-value="' + _hc + '" class="' + (_ilHlCol === _hc ? 'active' : '') + '" style="height:26px;padding:0;font-size:11px;box-sizing:border-box">' + _hc + '</button>';
                        }
                        html += '<input type="hidden" name="highlight_col" value="' + _ilHlCol + '">';
                        html += '</div>';
                    }
                    
                    var iconListItems = settings.items || [
                        {icon: 'circle', text: 'Feature one'},
                        {icon: 'circle', text: 'Feature two'},
                        {icon: 'circle', text: 'Feature three'}
                    ];
                    if (typeof iconListItems === 'string') {
                        try { iconListItems = JSON.parse(iconListItems); } catch(e) { iconListItems = []; }
                    }
                    
                    html += '<div class="impulse-table-editor" style="margin-top:6px">';
                    iconListItems.forEach(function(item, i) {
                        var iconName = item.icon || 'circle';
                        var hasUrl = !!(item.url);

                        
                        var rawText = String(item.text || '');
                        var plainText = rawText.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
                        var label = plainText || 'Item ' + (i + 1);
                        if (label.length > 24) label = label.substring(0, 22) + '...';
                        html += '<div class="impulse-table-item-edit' + (hasUrl ? ' impulse-url-mode' : '') + '" data-index="' + i + '" data-icon="' + iconName + '" data-url="' + (item.url || '').replace(/"/g, '&quot;') + '" style="margin-bottom:4px;display:flex;gap:4px;align-items:center">';
                        html += '<span class="impulse-table-drag" style="cursor: default;padding:2px;color:#666"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
                        html += '<button type="button" class="impulse-table-icon-btn" data-index="' + i + '" style="width:26px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.muted+';flex-shrink:0;box-sizing:border-box;position:relative">' + lucideSvg(iconName, 12) + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span></button>';
                        html += '<span class="impulse-table-label" style="flex:1;min-width:0;font-size:11px;color:'+ImpC.muted+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(label) + '</span>';
                        
                        html += '<input type="hidden" class="impulse-table-text" value="' + escapeHtml(item.text || '') + '">';
                        html += '<button type="button" class="impulse-table-url-btn' + (hasUrl ? ' impulse-url-active' : '') + '" style="width:26px;height:26px;flex-shrink:0;background:' + (hasUrl ? ''+ImpC.border+'' : ''+ImpC.panel+'') + ';border:1px solid ' + (hasUrl ? ''+ImpC.dim+'' : ''+ImpC.border+'') + ';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Toggle URL"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="' + (hasUrl ? ''+ImpC.white+'' : ''+ImpC.muted+'') + '" stroke-width="2.5"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></button>';
                        html += '<button type="button" class="impulse-remove-icon-list-item" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<button type="button" class="impulse-add-icon-list-item" style="width:100%;margin-top:4px;height:26px;padding:0 12px;background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;box-sizing:border-box">Add Item</button>';
                    if (ilCols >= 2) {
                        html += '<div style="margin-top:6px;font-size:10px;color:#666;text-align:center">Click text on screen to edit columns</div>';
                    }
                    html += '<input type="hidden" name="items" value=\'' + JSON.stringify(iconListItems).replace(/'/g, '&#39;') + '\'>';

                    

                    

                    

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;margin-top:12px;width:100%;box-sizing:border-box">';
                    
                    html += '<div style="justify-self:start;text-align:left">';
                    html +=   '<div style="font-size:11px;color:#888;margin-bottom:4px">Icon</div>';
                    html +=   settingColorSwatchOnly('icon_color', settings.icon_color || ''+ImpC.surface2+'');
                    html += '</div>';
                    
                    html += '<div style="justify-self:center;text-align:center">';
                    html +=   '<div style="font-size:11px;color:#888;margin-bottom:4px">Background</div>';
                    html +=   settingColorSwatchOnly('bg_color', settings.bg_color || '');
                    html += '</div>';
                    
                    html += '<div style="justify-self:end;text-align:right">';
                    html +=   '<div style="font-size:11px;color:#888;margin-bottom:4px">Text</div>';
                    html +=   settingColorSwatchOnly('text_color', settings.text_color || '#666666');
                    html += '</div>';
                    html += '</div>';

                    

                    
                    var hhEffect = settings.hover_highlight_effect || 'parallax';
                    if (['subtle','slide','glow','lift','stroke'].indexOf(hhEffect) !== -1) hhEffect = 'parallax';
                    if (hhEffect === 'burst' && !_ilShowIcons) hhEffect = 'parallax';
                    var _hhActive = !!settings.hover_highlight;
                    html += '<div style="margin-top:10px"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Hover Effect</label>';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="hover_highlight_effect" data-toggleable="1" data-toggle-default="' + hhEffect + '" style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px">';
                    [{v:'parallax',l:'Parallax'},{v:'burst',l:'Burst'},{v:'pop',l:'Pop'},{v:'tilt',l:'Tilt'}].forEach(function(o) {
                        var _disabled = (o.v === 'burst' && !_ilShowIcons);
                        var _active = (_hhActive && hhEffect === o.v);
                        var _cls = (_active ? 'active ' : '') + (_disabled ? 'impulse-btn-disabled' : '');
                        var _title = _disabled ? ' title="Burst radiates from icons — enable Show Icons to use this"' : '';
                        var _disAttr = _disabled ? ' disabled' : '';
                        var _disStyle = _disabled ? ';opacity:0.4;cursor:not-allowed' : '';
                        html += '<button type="button" data-value="' + o.v + '" class="' + _cls + '"' + _title + _disAttr + ' style="height:26px;padding:0;font-size:11px;box-sizing:border-box' + _disStyle + '">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="hover_highlight_effect" value="' + (_hhActive ? hhEffect : hhEffect) + '">';

                    html += '<input type="hidden" name="hover_highlight" value="' + (_hhActive ? '1' : '') + '">';
                    html += '</div></div>';

                    
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    if (ilCols >= 2) {
                        var _cfDef = function(c) { return (c === 1) ? 2 : 1; };
                        var _cfVal = function(c) {
                            var v = settings['col_flex_' + c];
                            return (v === undefined || v === '' || isNaN(parseFloat(v))) ? _cfDef(c) : parseFloat(v);
                        };
                        for (var _cw = 1; _cw <= ilCols; _cw++) {
                            html += settingSlider('col_flex_' + _cw, 'Col ' + _cw, _cfVal(_cw), 1, 8, '', true, false, _cfDef(_cw), undefined, 0.5);
                        }
                    }
                    html += settingSliderR('icon_size', 'Icon Size', settings, 20, 12, 32, 'px', true);
                    html += settingSliderR('text_size', 'Text Size', settings, 16, 12, 24, 'px', true);
                    html += settingSliderR('gap', 'Item Gap', settings, 12, 4, 32, 'px', true);
                    html += settingSliderR('icon_gap', 'Column Gap', settings, 12, 4, 24, 'px', true);

                    html += settingSliderR('padding', 'Padding', settings, 16, 0, 40, 'px', true);
                    html += settingSliderR('section_max_width', 'Max width', settings, 800, 200, 1600, 'px');
                    html += '</div>';

                    

                    html += '<div class="impulse-margin-grid impulse-hh-duration-wrap" style="display:' + (settings.hover_highlight ? 'grid' : 'none') + ';grid-template-columns:1fr">';
                    html += settingSliderR('hh_duration', 'Highlight', settings, 200, 50, 800, 'ms');
                    html += '</div>';
                    
                    var _staggerCb = '<label class="impulse-table-stagger-wrap" style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="stagger_items" class="impulse-checkbox"' + (settings.stagger_items ? ' checked' : '') + '> <span>Stagger items</span></label>';
                    html += settingEntranceAnimation(settings, _staggerCb);
                    break;

                case 'modal':
                    
                    html += '<div class="impulse-section-divider">Trigger</div>';
                    var popupTriggerVal = settings.trigger || 'click';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="trigger" style="display:flex;width:100%;gap:3px;margin-bottom:8px">';
                    [{v:'click',l:'Click'},{v:'timer',l:'Timer'},{v:'scroll',l:'Scroll'},{v:'exit',l:'Exit Intent'}].forEach(function(o) {
                        var tip = o.v === 'exit' ? ' data-tip="Triggers when cursor moves toward closing the tab"' : '';
                        html += '<button type="button" data-value="' + o.v + '"' + (popupTriggerVal === o.v ? ' class="active"' : '') + tip + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="trigger" value="' + popupTriggerVal + '">';
                    html += '</div>';

                    html += '<div class="impulse-modal-trigger-timer" style="display:' + (popupTriggerVal === 'timer' ? 'block' : 'none') + '">';
                    html += '<div class="impulse-margin-grid">' + settingSliderR('trigger_delay', 'Delay', settings, 3, 1, 30, 's', true) + '</div>';
                    html += '</div>';
                    html += '<div class="impulse-modal-trigger-scroll" style="display:' + (popupTriggerVal === 'scroll' ? 'block' : 'none') + '">';
                    html += '<div class="impulse-margin-grid">' + settingSliderR('trigger_scroll', 'Scroll %', settings, 50, 10, 100, '%', true) + '</div>';
                    html += '</div>';

                    

                    
                    html += '<div class="impulse-section-divider">Animation</div>';
                    var animVal = settings.popup_animation || 'depth';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="popup_animation" style="display:flex;width:100%;gap:3px;margin-bottom:8px">';
                    [{v:'depth',l:'Depth'},{v:'parallax',l:'Parallax'},{v:'tilt-fall',l:'Tilt-fall'},{v:'glass',l:'Glass'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (animVal === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box;min-width:0">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="popup_animation" value="' + animVal + '">';
                    html += '</div>';

                    

                    var posVal = settings.position || 'center';

                    
                    var _posCells = [
                        ['top-left',     'top-center',    'top-right'],
                        ['center-left',  'center',        'center-right'],
                        ['bottom-left',  'bottom-center', 'bottom-right']
                    ];
                    var _posTips = {
                        'center':        'Centred dialog',
                        'top-center':    'Top banner (full width)',
                        'bottom-center': 'Bottom banner (full width)',
                        'center-left':   'Left drawer (full height, off-canvas)',
                        'center-right':  'Right drawer (full height, off-canvas)',
                        'top-left':      'Top-left anchored popup (toast)',
                        'top-right':     'Top-right anchored popup (toast)',
                        'bottom-left':   'Bottom-left anchored popup (toast)',
                        'bottom-right':  'Bottom-right anchored popup (toast)'
                    };
                    var showCloseVal = settings.show_close === false || settings.show_close === '0' || settings.show_close === 0 ? false : true;
                    var closeOverlayVal = settings.close_on_overlay === false || settings.close_on_overlay === '0' || settings.close_on_overlay === 0 ? false : true;
                    var onceVal = settings.once_per_session === true || settings.once_per_session === '1' || settings.once_per_session === 1 ? true : false;

                    

                    html += '<div style="display:flex;align-items:stretch;gap:12px">';
                    html += '<div style="display:flex;flex-direction:column;justify-content:space-between;flex:1">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="show_close" class="impulse-checkbox"' + (showCloseVal ? ' checked' : '') + '> Close button</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="close_on_overlay" class="impulse-checkbox"' + (closeOverlayVal ? ' checked' : '') + '> Close on overlay click</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="once_per_session" class="impulse-checkbox"' + (onceVal ? ' checked' : '') + '> Once per session</label>';
                    
                    var autoDismissVal = settings.auto_dismiss === true || settings.auto_dismiss === '1' || settings.auto_dismiss === 1 ? true : false;
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="auto_dismiss" class="impulse-checkbox"' + (autoDismissVal ? ' checked' : '') + '> Auto-dismiss (toast)</label>';
                    html += '</div>';

                    html += '<div class="impulse-align-grid" data-name="overlay_position_grid" style="width:64px;height:64px;padding:8px;margin:0;flex-shrink:0;align-self:stretch">';
                    _posCells.forEach(function(row) {
                        row.forEach(function(v) {
                            if (!v) {
                                html += '<button type="button" class="impulse-align-dot" data-pos="" style="visibility:hidden;pointer-events:none" tabindex="-1"></button>';
                            } else {
                                var isActive = (posVal === v);
                                html += '<button type="button" class="impulse-align-dot' + (isActive ? ' active' : '') + '" data-pos="' + v + '" data-tip="' + (_posTips[v] || '') + '" style="width:8px;height:8px"></button>';
                            }
                        });
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="position" value="' + posVal + '">';
                    html += '</div>';

                    html += '<div class="impulse-modal-auto-dismiss" style="display:' + (autoDismissVal ? 'block' : 'none') + ';margin-top:6px">';
                    html += '<div class="impulse-margin-grid">' + settingSliderR('auto_dismiss_after', 'Dismiss after', settings, 4, 1, 15, 's', true) + '</div>';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:12px">';
                    html += '<div><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Overlay</label>' + settingColorSwatchOnly('overlay_color', settings.overlay_color || 'rgba(0,0,0,0.5)') + '</div>';
                    html += '<div style="text-align:right"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Background</label><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('popup_bg', settings.popup_bg || '#ffffff') + '</div></div>';
                    html += '</div>';

                    

                    
                    var _pv = posVal;
                    var _isCorner = ['top-left','top-right','bottom-left','bottom-right'].indexOf(_pv) !== -1;
                    var _isBanner = _pv === 'top-center' || _pv === 'bottom-center';
                    var _isDrawer = _pv === 'center-left' || _pv === 'center-right';
                    var _showWidth  = _pv === 'center' || _isDrawer || _isCorner;
                    var _showHeight = _pv === 'center' || _isBanner || _isCorner;
                    
                    var _widthDefault = (_pv === 'center') ? 500 : (_isCorner ? 360 : 420);
                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    if (_showWidth)  html += settingSliderR('popup_width',  'Width',  settings, _widthDefault, 200, 900, 'px', true);
                    if (_showHeight) html += settingSliderR('popup_height', 'Height', settings, 0, 0, 600, 'px', true);
                    
                    if (_showWidth !== _showHeight) html += '<div></div>';
                    html += '</div>';

                    
                    var _padLegacy = settings.popup_padding !== undefined && settings.popup_padding !== ''
                                   ? parseInt(settings.popup_padding) : null;
                    var _padHDefault = (_padLegacy !== null && !isNaN(_padLegacy)) ? _padLegacy : 24;
                    var _padVDefault = (_padLegacy !== null && !isNaN(_padLegacy)) ? _padLegacy : 24;
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('popup_padding_h', 'Padding H', settings, _padHDefault, 0, 60, 'px', true);
                    html += settingSliderR('popup_padding_v', 'Padding V', settings, _padVDefault, 0, 60, 'px', true);
                    html += '</div>';

                    
                    
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('popup_radius', 'Radius', settings, 0, 0, 30, 'px', true);
                    html += settingSliderR('popup_content_gap', 'Content Gap', settings, 8, 0, 60, 'px', true);
                    html += '</div>';

                    
                    
                    var _edgeFxVal = settings.overlay_edge_effect || '';
                    html += '<div style="font-size:11px;color:#888;margin:10px 0 4px">Edge effect</div>';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="overlay_edge_effect" data-toggleable="1" data-toggle-default="" style="display:flex;width:100%;gap:3px">';
                    [{v:'glow',l:'Glow'},{v:'specular',l:'Specular'},{v:'caustic',l:'Caustic'},{v:'pressure',l:'Pressure'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (_edgeFxVal === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box;min-width:0">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="overlay_edge_effect" value="' + _edgeFxVal + '">';
                    html += '</div>';

                    var popupId = settings.popup_id || ('popup-' + $('.impulse-panel-right').data('element-id'));
                    html += '<div class="impulse-section-divider">Popup Link</div>';
                    html += '<div style="display:flex;gap:4px;margin-bottom:4px">';
                    html += '<input type="text" name="popup_id" value="' + escapeHtml(popupId) + '" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box;font-family:monospace;line-height:26px">';
                    html += '<button type="button" class="instinctor-btn impulse-copy-popup-id" style="height:26px;padding:0 8px;font-size:11px;white-space:nowrap;line-height:26px;box-sizing:border-box" title="Copy link target">Copy #</button>';
                    html += '</div>';
                    html += '<p class="impulse-setting-hint">Set any button\'s link to <span style="color:'+ImpC.text+';font-family:monospace">#' + escapeHtml(popupId) + '</span></p>';
                    html += settingBgShapes(settings);
                    break;

                case 'modal':
                    
                    html += '<div class="impulse-section-divider">Position</div>';
                    var ocPos = settings.oc_position || 'right';
                    html += '<div class="impulse-btn-group" data-name="oc_position" style="display:flex;width:100%;gap:3px">';
                    [{v:'left',l:'Left'},{v:'right',l:'Right'}].forEach(function(o) {
                        html += '<button type="button" class="' + (ocPos === o.v ? 'active' : '') + '" data-value="' + o.v + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="oc_position" value="' + ocPos + '">';
                    html += '</div>';

                    html += '<div class="impulse-section-divider">Size</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('oc_width', 'Width', settings, 360, 200, 600, 'px', true);
                    html += settingSliderR('oc_padding', 'Padding', settings, 24, 0, 60, 'px', true);
                    html += '</div>';

                    html += '<div class="impulse-section-divider">Options</div>';
                    var ocShowClose = settings.oc_show_close !== false && settings.oc_show_close !== '0' && settings.oc_show_close !== 0;
                    var ocShowOverlay = settings.oc_show_overlay !== false && settings.oc_show_overlay !== '0' && settings.oc_show_overlay !== 0;
                    var ocCloseOverlay = settings.oc_close_on_overlay !== false && settings.oc_close_on_overlay !== '0' && settings.oc_close_on_overlay !== 0;
                    html += '<div style="display:flex;flex-direction:column;gap:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="oc_show_close" class="impulse-checkbox"' + (ocShowClose ? ' checked' : '') + '> Close button</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="oc_show_overlay" class="impulse-checkbox"' + (ocShowOverlay ? ' checked' : '') + '> Show overlay</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer"><input type="checkbox" name="oc_close_on_overlay" class="impulse-checkbox"' + (ocCloseOverlay ? ' checked' : '') + '> Close on overlay click</label>';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:12px">';
                    html += '<div><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Background</label>' + settingColorSwatchOnly('oc_bg', settings.oc_bg || '#ffffff') + '</div>';
                    html += '<div style="text-align:right"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Overlay</label><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('oc_overlay_color', settings.oc_overlay_color || 'rgba(0,0,0,0.4)') + '</div></div>';
                    html += '</div>';

                    var ocId = settings.oc_id || ('offcanvas-' + $('.impulse-panel-right').data('element-id'));
                    html += '<div class="impulse-section-divider">Trigger Link</div>';
                    html += '<div style="display:flex;gap:4px;margin-bottom:4px">';
                    html += '<input type="text" name="oc_id" value="' + escapeHtml(ocId) + '" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box;font-family:monospace;line-height:26px">';
                    html += '<button type="button" class="instinctor-btn impulse-copy-popup-id" style="height:26px;padding:0 8px;font-size:11px;white-space:nowrap;line-height:26px;box-sizing:border-box" title="Copy link target">Copy #</button>';
                    html += '</div>';
                    html += '<p class="impulse-setting-hint">Set any button\'s link to <span style="color:'+ImpC.text+';font-family:monospace">#' + escapeHtml(ocId) + '</span></p>';
                    html += settingBgShapes(settings);
                    break;

                case 'plans':
                    
                    var plans = settings.plans || [];
                    if (typeof plans === 'string') {
                        try { plans = JSON.parse(plans); } catch(e) { plans = []; }
                    }
                    
                    if (plans.length === 0) {
                        plans = [
                            { title: 'Basic', subtitle: 'For individuals', price: '19', currency: '$', period: '/month', yearly_price: '190', yearly_period: '/year', features: [{text:'5 Projects',status:'included'},{text:'10GB Storage',status:'included'},{text:'Email Support',status:'included'},{text:'Priority Support',status:'excluded'}], button_text: 'Get Started', button_link: '#', ribbon: 'none' },
                            { title: 'Pro', subtitle: 'For small teams', price: '49', currency: '$', period: '/month', yearly_price: '490', yearly_period: '/year', features: [{text:'Unlimited Projects',status:'included'},{text:'100GB Storage',status:'included'},{text:'Priority Support',status:'included'},{text:'API Access',status:'included'}], button_text: 'Get Started', button_link: '#', ribbon: 'popular', highlighted: true },
                            { title: 'Enterprise', subtitle: 'For large teams', price: '99', currency: '$', period: '/month', yearly_price: '990', yearly_period: '/year', features: [{text:'Everything in Pro',status:'included'},{text:'Unlimited Storage',status:'included'},{text:'Dedicated Support',status:'included'},{text:'Custom Integrations',status:'included'}], button_text: 'Contact Sales', button_link: '#', ribbon: 'none' }
                        ];
                    }
                    
                    html += '<div class="impulse-setting-label">Tiers</div>';
                    html += '<div class="impulse-pricing-plans-list">';
                    plans.forEach(function(plan, i) {
                        html += '<div class="impulse-pricing-plan-item" data-index="' + i + '" style="margin-bottom:6px;display:flex;gap:5px;align-items:center">';
                        html += '<div class="impulse-pricing-plan-name-wrap" style="flex:1;position:relative">';
                        html += '<input type="text" class="impulse-pricing-plan-title" data-index="' + i + '" value="' + (plan.title || 'Plan').replace(/"/g, '&quot;') + '" style="width:100%;height:26px;padding:0 24px 0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                        if (plans.length > 1) {
                            html += '<button type="button" class="impulse-remove-pricing-plan" data-index="' + i + '" title="Remove"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>';
                        }
                        html += '</div>';
                        html += '<button type="button" class="impulse-edit-pricing-plan" data-index="' + i + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Edit"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg></button>';
                        html += '<button type="button" class="impulse-duplicate-pricing-plan" data-index="' + i + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Duplicate"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button>';
                        html += '</div>';
                    });
                    html += '</div>';
                    if (plans.length < 4) {
                        html += '<button type="button" class="impulse-add-pricing-plan" style="width:100%;margin-top:6px;height:26px;padding:0 12px;background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;box-sizing:border-box">Add Plan</button>';
                    }
                    html += '<input type="hidden" name="plans" value=\'' + JSON.stringify(plans).replace(/'/g, '&#39;') + '\'>';

                    html += '<div style="margin-top:12px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+'"><input type="checkbox" name="show_toggle"' + (settings.show_toggle ? ' checked' : '') + ' style="margin:0;accent-color:#666"> Monthly/Yearly</label>';
                    html += '</div>';

                    html += '<div class="impulse-yearly-discount-setting" style="margin-top:8px;' + (!settings.show_toggle ? 'display:none' : '') + '">';
                    html += '<div style="display:grid;grid-template-columns:1fr auto;gap:16px;align-items:end">';
                    
                    html += '<div>' + settingText('yearly_label', 'Yearly Label', settings.yearly_label || 'Save 20%') + '</div>';
                    
                    html += '<div style="text-align:right"><div style="font-size:11px;color:'+ImpC.muted+';margin-bottom:6px">Ribbon</div>';
                    var ribbonVal = settings.ribbon_style || 'banner';
                    html += '<div class="impulse-btn-group" data-name="ribbon_style" data-toggleable="1" style="display:flex;gap:3px">';
                    [{v:'banner',l:'Banner'},{v:'corner',l:'Corner'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (ribbonVal === o.v ? ' class="active"' : '') + '>' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="ribbon_style" value="' + ribbonVal + '">';
                    html += '</div></div>';
                    html += '</div></div>';

                    
                    
                    html += '<div class="impulse-section-divider">Card</div>';
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px">';
                    html += '<div style="text-align:left"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Background</div>' + settingColorSwatchOnly('bg_color', settings.bg_color || '#ffffff') + '</div>';
                    html += '<div style="text-align:center"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Text</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('text_color', settings.text_color || '#666666') + '</div></div>';
                    html += '<div style="text-align:right"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Button</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('button_bg', settings.button_bg || ''+ImpC.surface2+'') + '</div></div>';
                    html += '</div>';

                    var hasHighlighted = plans.some(function(p) { return p.highlighted; });
                    if (hasHighlighted) {
                    html += '<div class="impulse-section-divider">Highlighted Card</div>';
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px">';
                    html += '<div style="text-align:left"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Background</div>' + settingColorSwatchOnly('highlight_bg', settings.highlight_bg || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="text-align:center"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Text</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('highlight_color', settings.highlight_color || '#ffffff') + '</div></div>';
                    html += '<div style="text-align:right"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Button</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('highlight_button_bg', settings.highlight_button_bg || '#ffffff') + '</div></div>';
                    html += '</div>';
                    }

                    html += '<div class="impulse-section-divider">Hover</div>';
                    var hoverVal = settings.hover_effect || 'none';
                    html += '<div class="impulse-btn-group" data-name="hover_effect" data-toggleable="1" style="display:flex;width:100%;gap:3px">';
                    [{v:'lift',l:'Lift'},{v:'tilt',l:'Tilt'},{v:'glow',l:'Glow'},{v:'float',l:'Float'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (hoverVal === o.v ? ' class="active"' : '') + ' style="flex:1">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="hover_effect" value="' + hoverVal + '">';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('section_max_width', 'Max width', settings, 1200, 200, 1600, 'px');
                    html += settingSliderR('border_radius', 'Radius', settings, 4, 0, 24, 'px');
                    html += settingSliderR('price_size', 'Price size', settings, 38, 20, 64, 'px');
                    html += settingSliderR('btn_font_size', 'Button size', settings, 14, 10, 20, 'px');
                    html += settingSliderR('btn_padding_v', 'Button pad', settings, 14, 6, 24, 'px');

                    

                    html += settingSliderR('arc_intensity', 'Arc', settings, 0, 0, 100, '%');
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    break;

                case 'title':
                    var laPs = settings.la_preset || '';
                    var laCt = settings.la_content_type || 'text';
                    
                    html += '<div class="impulse-btn-group" data-name="la_content_type" style="display:grid;grid-template-columns:1fr 1fr;gap:3px;margin-bottom:8px">';
                    html += '<button type="button" class="' + (laCt==='text' ? 'active' : '') + '" data-value="text" style="height:26px;font-size:11px">Text</button>';
                    html += '<button type="button" class="' + (laCt==='image' ? 'active' : '') + '" data-value="image" style="height:26px;font-size:11px">Image</button>';
                    html += '<input type="hidden" name="la_content_type" value="' + laCt + '">';
                    html += '</div>';
                    
                    var laAlign = settings.align || 'center';
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="align" style="margin-bottom:8px;display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + (laAlign === 'left' ? 'active' : '') + '" data-value="left" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + (laAlign === 'center' ? 'active' : '') + '" data-value="center" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="10" x2="6" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="18" y1="18" x2="6" y2="18"/></svg></button>';
                    html += '<button type="button" class="' + (laAlign === 'right' ? 'active' : '') + '" data-value="right" style="flex:1;height:26px;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="21" y1="10" x2="7" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="7" y2="18"/></svg></button>';
                    html += '<input type="hidden" name="align" value="' + laAlign + '">';
                    html += '</div>';

                    

                    html += '<div class="la-text-settings" style="' + (laCt==='image' ? 'display:none' : '') + '">';
                    html += '<div class="impulse-setting-row">';

                    

                    

                    

                    
                    
                    html += '<textarea name="la_text" placeholder="Your text" rows="2" style="width:100%;min-height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';color:'+ImpC.text+';border-radius:3px;padding:5px 8px;font-size:12px;box-sizing:border-box;resize:vertical;font-family:inherit;line-height:1.4">' + escapeHtml(settings.la_text || '') + '</textarea>';
                    html += '</div>';
                    
                    var laW = settings.la_font_weight || '700';
                    var _laFont = settings.font_family || '';
                    html += '<div style="display:flex;align-items:center;gap:6px;margin-bottom:8px">';
                    html += '<div style="flex-shrink:0;height:26px;overflow:hidden">' + settingColorSwatchOnly('la_color', settings.la_color || '#1d2327') + '</div>';
                    html += '<div style="flex-shrink:0;height:26px">' + settingColorSwatchOnly('la_gradient_to', settings.la_gradient_to || '') + '</div>';
                    html += '<div class="impulse-btn-group la-font-weight-wrap" data-name="la_font_weight" style="display:flex;flex:1;gap:0">';
                    html += '<button type="button" class="' + (laW==='400' ? 'active' : '') + '" data-value="400" style="flex:1;height:26px;padding:0;font-size:11px;font-weight:400' + (_fontHasWeight(_laFont,'400') ? '' : ';opacity:0.2;pointer-events:none') + '">Regular</button>';
                    html += '<button type="button" class="' + (laW==='700' ? 'active' : '') + '" data-value="700" style="flex:1;height:26px;padding:0;font-size:11px;font-weight:700' + (_fontHasWeight(_laFont,'700') ? '' : ';opacity:0.2;pointer-events:none') + '">Bold</button>';
                    html += '<button type="button" class="' + (laW==='900' ? 'active' : '') + '" data-value="900" style="flex:1;height:26px;padding:0;font-size:11px;font-weight:900' + (_fontHasWeight(_laFont,'900') ? '' : ';opacity:0.2;pointer-events:none') + '">Black</button>';
                    html += '<input type="hidden" name="la_font_weight" value="' + laW + '">';
                    html += '</div>';
                    html += '</div>';

                    
                    html += '<div class="la-grad-angle-row" style="' + (settings.la_gradient_to ? '' : 'display:none') + '">';
                    html += '<div class="impulse-margin-grid" style="margin-top:0">';
                    html += settingSliderR('la_gradient_angle', 'Grad Angle', settings, 135, 0, 360, '°');
                    html += '</div></div>';
                    html += settingFontPicker('font_family', settings.font_family || '');
                    html += '</div>';

                    html += '<div class="la-image-settings" style="' + (laCt==='text' ? 'display:none' : '') + '">';
                    html += '<input type="hidden" name="la_svg_colors" value="' + escapeHtml(settings.la_svg_colors || '') + '">';
                    var _laSvgSrc = settings.la_image_src || '';
                    var _isSvgImg = _laSvgSrc && /\.svg(\?|$)/i.test(_laSvgSrc);
                    var _svgColorsRaw = _isSvgImg ? (settings.la_svg_colors || '') : '';
                    var _svgMap = {};
                    try { if (_svgColorsRaw) _svgMap = JSON.parse(_svgColorsRaw); } catch(e) {}
                    var _svgOrig = Object.keys(_svgMap);
                    
                    var _imgVal = settings.la_image_src || '';
                    html += '<div class="impulse-setting-row impulse-image-setting" data-name="la_image_src" style="align-items:flex-start">';
                    html += '<label style="padding-top:5px">Image</label>';
                    html += '<input type="hidden" name="la_image_src" value="' + escapeHtml(_imgVal) + '">';
                    if (_imgVal) {
                        html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="la_image_src" style="display:none;height:26px">Select</button>';
                        
                        html += '<div class="impulse-image-preview" style="display:flex;flex-wrap:wrap;align-items:center;gap:4px">';
                        html += '<button type="button" class="impulse-remove-image-btn" data-name="la_image_src" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button>';
                        if (_isSvgImg) {
                            if (_svgOrig.length) {
                                _svgOrig.forEach(function(orig, i) {
                                    var cur = _svgMap[orig] || orig;
                                    html += settingColorSwatchOnly('la_svg_color_' + i, cur, orig);
                                    html += '<input type="hidden" name="la_svg_orig_' + i + '" value="' + escapeHtml(orig) + '">';
                                });
                            } else {
                                html += '<span id="impulse-la-svg-pending" data-url="' + escapeHtml(_laSvgSrc) + '" style="font-size:11px;color:#888">Loading…</span>';
                            }
                        }
                        html += '</div>';
                    } else {
                        html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="la_image_src" style="height:26px">Select</button>';
                    }
                    html += '</div>';
                    html += '</div>';

                    html += '<div class="impulse-section-divider" style="margin-top:10px">Animation</div>';

                    var laPresets = [
                        {id:'build_columns',     label:'Columns'},
                        {id:'build_glitch',      label:'Glitch'},
                        {id:'build_decode',      label:'Decode'},
                        {id:'build_slots',       label:'Slots'},
                        {id:'build_streaks',     label:'Streaks'},
                        {id:'build_dissolve',    label:'Dissolve'},
                        {id:'build_emerge',      label:'Emerge'},
                        {id:'build_zslices',     label:'Layers'},
                        {id:'build_converge',    label:'Converge'},
                        {id:'mask_iris',         label:'Iris'},
                        {id:'voronoi_pop',       label:'Cells'},
                        {id:'warp_pinch',        label:'Pinch'},
                        {id:'dof_rack',          label:'Focus'},
                        {id:'dof_tilt',          label:'Tilt'},
                        {id:'noise_elastic',     label:'Elastic'},
                        {id:'fx_noise',          label:'Noise'},
                        {id:'fx_ripple',         label:'Ripple'},
                        {id:'fx_liquid',         label:'Liquid'},
                        {id:'fx_shatter',        label:'Shatter'},
                        {id:'fx_static',         label:'Static'},
                        {id:'fx_melt',           label:'Melt'},
                        {id:'fx_glass',          label:'Glass'},
                        {id:'fx_wave',           label:'Wave'},
                        {id:'fx_smoke',          label:'Smoke'},
                        {id:'fx_storm',          label:'Storm'},
                        {id:'fx_warp',           label:'Warp'},
                        {id:'3d_depth_in',    label:'Depth'},
                        {id:'3d_zoom_out',    label:'Zoom Out'},
                        {id:'3d_flip_x',      label:'Flip X'},
                        {id:'3d_spin_in',     label:'Spin'},
                        {id:'3d_swing',       label:'Swing'},
                        {id:'3d_unfold',      label:'Unfold'},
                        {id:'3d_curtain',     label:'Curtain'},
                        {id:'3d_bounce',      label:'Bounce'},
                        {id:'3d_rain',        label:'Rain'},
                        {id:'3d_stagger_h',   label:'Rows'},
                        {id:'3d_explode_in',  label:'Explode'},
                        {id:'3d_crystal',     label:'Crystal'},
                        {id:'3d_unfurl',      label:'Unfurl'},
                        {id:'3d_lightfield',  label:'Light Field'},
                        {id:'neon_ignite',    label:'Neon'}];

                    html += '<div class="impulse-btn-group" data-name="la_preset" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px">';
                    laPresets.forEach(function(p) {
                        if (p.sep) {
                            var _sepStyle = p.sub
                                ? 'grid-column:1/-1;font-size:10px;color:'+ImpC.dim+';padding:5px 0 1px;margin-top:2px'
                                : 'grid-column:1/-1;font-size:10px;color:'+ImpC.dim+';text-transform:uppercase;letter-spacing:0.08em;padding:6px 0 2px;border-top:1px solid '+ImpC.panel+';margin-top:4px';
                            html += '<div style="' + _sepStyle + '">' + p.label + '</div>';
                            return;
                        }
                        html += '<button type="button" class="impulse-la-preset-btn' + (laPs===p.id ? ' active' : '') + '" data-value="' + p.id + '">' + p.label + '</button>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="la_preset" value="' + laPs + '">';

                    
                    
                    html += '<input type="hidden" name="la_scroll_trigger" value="1">';
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    
                    html += '<div class="la-text-settings" style="' + (laCt==='image' ? 'display:none' : '') + '">';
                    html += settingSliderR('la_font_size', 'Size', settings, 64, 12, 200, 'px', true);
                    html += '</div>';
                    html += '<div class="la-image-settings" style="' + (laCt==='text' ? 'display:none' : '') + '">';
                    html += settingSliderR('la_image_width', 'Width', settings, 280, 40, 800, 'px', true);
                    html += '</div>';
                    html += settingSlider('la_duration', 'Duration', (function(){ var v=parseFloat(getResponsiveValue(settings,'la_duration',1.2)); return v>10?Math.round(v/100)/10:v||1.2; })(), 0.2, 5, 's', false, true, 1.2, false, 0.1);
                    html += settingSlider('la_delay', 'Delay', (function(){ var v=parseFloat(getResponsiveValue(settings,'la_delay',0)); return v>10?Math.round(v/100)/10:v; })(), 0, 5, 's', false, true, 0, false, 0.1);
                    html += settingSliderR('la_spring', 'Spring', settings, 5, 0, 20, '');
                    html += settingSliderR('la_tilt', 'Mouse Tilt', settings, 0, 0, 30, '°');
                    html += settingSliderR('la_depth', 'Depth', settings, 50, 0, 100, '');
                    
                    html += settingSliderR('la_gap_below', 'Gap Below', settings, 0, 0, 120, 'px', false);

                    
                    
                    html += settingSliderR('text_halo', 'Halo', settings, 0, 0, 100, '%', true, 'Soft glow around the animator content for legibility on busy backgrounds');
                    html += '</div>';

                    break;
                
                case 'flip_box':
                    var animType = settings.animation_type || 'spring';
                    var bStyle = 'flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box';
                    function flipBtn(val, label) {
                        return '<button type="button" class="' + (animType === val ? 'active' : '') + '" data-value="' + val + '" style="' + bStyle + '">' + label + '</button>';
                    }

                    
                    
                    html += '<div class="impulse-btn-group" data-name="animation_type" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px">';
                    
                    html += flipBtn('zoom','Zoom');
                    
                    html += '<input type="hidden" name="animation_type" value="' + animType + '">';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid">';
                    html += settingSlider('animation_speed', 'Speed', parseInt(settings.animation_speed)||900, 150, 1400, 'ms', false, false, 900, null, 50);
                    html += '</div>';

                    var showFlipDir = ['spring','cube'].indexOf(animType) !== -1;
                    html += '<div class="impulse-flip-direction-setting" style="margin-top:8px;' + (!showFlipDir ? 'display:none' : '') + '">';
                    html += '<div class="impulse-btn-group" data-name="flip_direction" style="display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + ((settings.flip_direction || 'horizontal') === 'horizontal' ? 'active' : '') + '" data-value="horizontal" style="' + bStyle + '">Horizontal</button>';
                    html += '<button type="button" class="' + ((settings.flip_direction || 'horizontal') === 'vertical' ? 'active' : '') + '" data-value="vertical" style="' + bStyle + '">Vertical</button>';
                    html += '<input type="hidden" name="flip_direction" value="' + (settings.flip_direction || 'horizontal') + '">';
                    html += '</div></div>';

                    var showSlideDir = animType === 'push';
                    html += '<div class="impulse-slide-direction-setting" style="margin-top:8px;' + (!showSlideDir ? 'display:none' : '') + '">';
                    html += '<div class="impulse-btn-group" data-name="slide_direction" style="display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + ((settings.slide_direction || 'left') === 'left' ? 'active' : '') + '" data-value="left" style="' + bStyle + '">Left</button>';
                    html += '<button type="button" class="' + ((settings.slide_direction || 'left') === 'right' ? 'active' : '') + '" data-value="right" style="' + bStyle + '">Right</button>';
                    html += '<button type="button" class="' + ((settings.slide_direction || 'left') === 'up' ? 'active' : '') + '" data-value="up" style="' + bStyle + '">Up</button>';
                    html += '<button type="button" class="' + ((settings.slide_direction || 'left') === 'down' ? 'active' : '') + '" data-value="down" style="' + bStyle + '">Down</button>';
                    html += '<input type="hidden" name="slide_direction" value="' + (settings.slide_direction || 'left') + '">';
                    html += '</div></div></div>';

                    html += '<div class="impulse-style-subtabs-wrap" style="margin-top:12px">';
                    html += '<div class="impulse-settings-subtabs">';
                    html += '<button type="button" class="impulse-settings-subtab active" data-tab="front">Front</button>';
                    html += '<button type="button" class="impulse-settings-subtab" data-tab="back">Back</button>';
                    html += '</div>';

                    

                    
                    
                    html += '<div class="impulse-subtab-content active" data-tab="front">';
                    html += '<div style="margin:12px 0">';
                    html += settingRichText('front_title', '', settings.front_title || '', {
                        rows: 3,
                        placeholder: 'Front text'
                    });
                    html += '</div>';

                    
                    html += '<input type="hidden" name="front_content" value="' + escapeHtml(settings.front_content || '') + '">';
                    html += '<div class="impulse-card-row-double" style="margin-top:12px">';
                    html += settingColorSwatch('front_bg', 'Background', settings.front_bg || ''+ImpC.light+'', true, true);
                    html += settingColorSwatch('front_color', 'Text', settings.front_color || ''+ImpC.surface2+'', true, false);
                    html += '</div>';
                    html += '</div>';

                    
                    html += '<div class="impulse-subtab-content" data-tab="back">';
                    html += '<div style="margin:12px 0">';
                    html += settingRichText('back_title', '', settings.back_title || '', {
                        rows: 3,
                        placeholder: 'Back text'
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="back_content" value="' + escapeHtml(settings.back_content || '') + '">';
                    html += '<div class="impulse-setting-row"><input type="text" name="back_button_text" value="' + escapeHtml(settings.back_button_text || '') + '" placeholder="Button Text" style="font-size:11px"></div>';
                    html += '<div class="impulse-setting-row"><input type="text" name="back_button_link" value="' + escapeHtml(settings.back_button_link || '#') + '" placeholder="Button Link" style="font-size:11px"></div>';
                    html += '<div class="impulse-card-row-double" style="margin-top:12px">';
                    html += settingColorSwatch('back_bg', 'Background', settings.back_bg || ''+ImpC.text+'', true, true);
                    html += settingColorSwatch('back_color', 'Text', settings.back_color || ''+ImpC.surface2+'', true, false);
                    html += '</div>';
                    html += '</div>';
                    html += '</div>'; 

                    
                    
                    var frostedOn = !!settings.frosted_glass;
                    html += '<div style="margin-top:10px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer">'
                          + '<input type="checkbox" name="frosted_glass" class="impulse-checkbox"' + (frostedOn ? ' checked' : '') + '>'
                          + '<span>Frosted Glass</span></label>';
                    html += '</div>';

                    
                    var vAlign = settings.vertical_align || 'top';
                    html += '<div style="margin-top:10px">';
                    html += '<label style="font-size:11px;color:'+ImpC.muted+';margin-bottom:4px;display:block">Vertical align</label>';
                    html += '<div class="impulse-btn-group" data-name="vertical_align" style="display:flex;gap:3px">';
                    ['top','center','bottom'].forEach(function(v) {
                        html += '<button type="button" class="' + (vAlign === v ? 'active' : '') + '" data-value="' + v + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + v.charAt(0).toUpperCase() + v.slice(1) + '</button>';
                    });
                    html += '<input type="hidden" name="vertical_align" value="' + vAlign + '">';
                    html += '</div></div>';

                    html += '<div class="impulse-padding-grid" style="margin-top:12px">';
                    html += settingSliderR('height', 'Height', settings, 250, 70, 500, 'px');
                    html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 30, 'px');
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += '<div>' + settingSliderR('front_title_size', 'Title Size', settings, 24, 12, 72, 'px', true) + '</div>';
                    html += '<div>' + settingSliderR('front_content_size', 'Content Size', settings, 14, 10, 32, 'px', true) + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += '<div>' + settingSliderR('section_max_width', 'Max Width', settings, 600, 200, 1200, 'px', true) + '</div>';
                    html += '<div>' + settingSliderR('padding', 'Padding', settings, 32, 0, 80, 'px', true) + '</div>';
                    html += '</div>';
                    html += settingBorder('', settings);
                    break;
                
                case 'social':
                    html += '<div style="font-size:11px;color:'+ImpC.dim+';margin-bottom:10px;padding:6px 8px;background:'+ImpC.surface+';border-radius:3px">Add social profiles in <span class=\"impulse-goto-seo-site\" style=\"color:'+ImpC.muted+';cursor:pointer;text-decoration:underline;text-underline-offset:2px\">Settings</span></div>';

                    html += '<div class="impulse-btn-group" data-name="bg_shape" data-toggleable="1" style="display:flex;width:100%;gap:3px;margin-bottom:6px">';
                    [{v:'circle',l:'Circle'},{v:'rounded',l:'Rounded'},{v:'square',l:'Square'}].forEach(function(opt) {
                        html += '<button type="button" data-value="' + opt.v + '"' + ((settings.bg_shape || 'none') === opt.v ? ' class="active"' : '') + ' style="flex:1;height:26px;box-sizing:border-box">' + opt.l + '</button>';
                    });
                    html += '<input type="hidden" name="bg_shape" value="' + (settings.bg_shape || 'none') + '">';
                    html += '</div>';

                    html += '<div class="impulse-btn-group" data-name="align" style="display:flex;width:100%;gap:3px;margin-bottom:6px">';
                    ['left','center','right'].forEach(function(v) {
                        html += '<button type="button" data-value="' + v + '"' + ((settings.align || 'center') === v ? ' class="active"' : '') + ' style="flex:1;height:26px;box-sizing:border-box">' + v.charAt(0).toUpperCase() + v.slice(1) + '</button>';
                    });
                    html += '<input type="hidden" name="align" value="' + (settings.align || 'center') + '">';
                    html += '</div>';

                    var socHoverVal = settings.hover_effect || 'none';
                    html += '<div class="impulse-btn-group" data-name="hover_effect" data-toggleable="1" style="display:flex;width:100%;gap:3px;margin-bottom:6px">';
                    [{v:'shine',l:'Shine'},{v:'spin',l:'Spin'},{v:'grow',l:'Grow'}].forEach(function(e) {
                        html += '<button type="button" class="' + (socHoverVal === e.v ? 'active' : '') + '" data-value="' + e.v + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + e.l + '</button>';
                    });
                    html += '<input type="hidden" name="hover_effect" value="' + socHoverVal + '">';
                    html += '</div>';

                    var brandOn = !!settings.brand_colors;
                    html += '<div style="margin-bottom:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="brand_colors" class="impulse-checkbox"' + (brandOn ? ' checked' : '') + '><span>Brand Colors</span></label>';
                    html += '</div>';

                    html += '<div style="display:flex;gap:8px">';
                    html += '<div style="flex:1">';
                    html += '<div class="impulse-setting-label" style="margin-bottom:4px">Color</div>';
                    html += settingColorSwatchOnly('icon_color', settings.icon_color || ''+ImpC.surface2+'');
                    html += '</div>';
                    html += '<div style="flex:1' + (brandOn ? ';opacity:0.3;pointer-events:none' : '') + '">';
                    html += '<div class="impulse-setting-label" style="margin-bottom:4px;text-align:center">Hover</div>';
                    html += '<div style="display:flex;justify-content:center">' + settingColorSwatchOnly('hover_color', settings.hover_color || '#666666') + '</div>';
                    html += '</div>';
                    html += '<div style="flex:1">';
                    html += '<div class="impulse-setting-label" style="margin-bottom:4px;text-align:right">Background</div>';
                    html += '<div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('bg_color', settings.bg_color || '') + '</div>';
                    html += '</div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += settingSliderR('icon_size', 'Size', settings, 24, 16, 48, 'px', true);
                    html += settingSliderR('gap', 'Gap', settings, 12, 4, 32, 'px', true);
                    html += '</div>';
                    html += settingEntranceAnimation(settings);
                    break;

                case 'map':
                    
                    html += '<div style="margin-bottom:8px">';
                    html += '<label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Address</label>';
                    html += '<input type="text" name="address" value="' + escapeHtml(settings.address || '1600 Amphitheatre Parkway, Mountain View, CA') + '" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '</div>';

                    var mapShape = settings.map_shape || 'rectangle';
                    
                    if (mapShape === 'none' || mapShape === 'soft') mapShape = 'rectangle';
                    html += '<div style="display:flex;gap:8px;margin-top:6px">';
                    html += '<div style="flex:1">';
                    html += '<div class="impulse-btn-group" data-name="map_shape" style="display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + (mapShape === 'rectangle' ? 'active' : '') + '" data-value="rectangle" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Rectangle</button>';
                    html += '<button type="button" class="' + (mapShape === 'circle' ? 'active' : '') + '" data-value="circle" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Circle</button>';
                    html += '<input type="hidden" name="map_shape" value="' + mapShape + '">';
                    html += '</div></div>';
                    
                    var mapStyle = settings.map_style || 'normal';
                    if (mapStyle === 'dark') mapStyle = 'normal';
                    html += '<div style="flex:1">';
                    html += '<div class="impulse-btn-group" data-name="map_style" style="display:flex;width:100%;gap:3px">';
                    html += '<button type="button" class="' + (mapStyle === 'normal' ? 'active' : '') + '" data-value="normal" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Color</button>';
                    html += '<button type="button" class="' + (mapStyle === 'grey' ? 'active' : '') + '" data-value="grey" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">Grey</button>';
                    html += '<input type="hidden" name="map_style" value="' + mapStyle + '">';
                    html += '</div></div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += settingSliderR('zoom', 'Zoom', settings, 14, 1, 20, '', true);
                    html += settingSliderR('map_height', 'Height', settings, 400, 100, 800, 'px', true);
                    if (mapShape !== 'circle') {
                        html += settingSliderR('width', 'Width', settings, 100, 20, 100, '%', true);
                        html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 50, 'px', true);
                    }
                    html += '</div>';

                    var mapAlign = settings.position_align || 'center';
                    html += '<div style="margin-top:8px"><label style="display:block;margin-bottom:4px;font-size:11px;color:#888">Position</label>';
                    html += '<div class="impulse-btn-group" data-name="position_align" style="display:flex;gap:2px">';
                    html += '<button type="button" class="' + (mapAlign === 'left' ? 'active' : '') + '" data-value="left" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12H3m0 0 4-4m-4 4 4 4"/></svg></button>';
                    html += '<button type="button" class="' + (mapAlign === 'center' ? 'active' : '') + '" data-value="center" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 3v18M3 12h18"/></svg></button>';
                    html += '<button type="button" class="' + (mapAlign === 'right' ? 'active' : '') + '" data-value="right" style="width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;box-sizing:border-box"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 12h18m0 0-4-4m4 4-4 4"/></svg></button>';
                    html += '<input type="hidden" name="position_align" value="' + mapAlign + '">';
                    html += '</div></div>';
                    break;
                    
                case 'slider':
                    
                case 'carousel':
                    var _carCt = settings.content_type || 'images';

                    html += '<div class="impulse-btn-group" data-name="content_type" style="display:grid;grid-template-columns:1fr 1fr;gap:3px;margin-bottom:10px">';
                    html += '<button type="button" class="' + (_carCt === 'images' ? 'active' : '') + '" data-value="images" style="height:26px;font-size:11px">Images</button>';
                    html += '<button type="button" class="' + (_carCt === 'data' ? 'active' : '') + '" data-value="data" style="height:26px;font-size:11px">Slides</button>';
                    html += '<input type="hidden" name="content_type" value="' + _carCt + '">';
                    html += '</div>';

                    html += '<div class="impulse-carousel-images-section"' + (_carCt !== 'images' ? ' style="display:none"' : '') + '>';

                    html += '<button type="button" class="instinctor-btn" id="impulse-select-carousel-images" style="width:100%">Add Images</button>';
                    html += '<div class="impulse-carousel-images-list" style="margin-top:5px">';
                    var images = settings.images || [];
                    if (typeof images === 'string') {
                        try { images = JSON.parse(images); } catch(e) { images = []; }
                    }
                    if (!Array.isArray(images)) images = [];
                    images.forEach(function(img, i) {
                        html += '<div class="impulse-carousel-image-item" data-index="' + i + '" style="display:flex;gap:6px;align-items:center;margin-bottom:5px">';
                        html += '<img src="' + (img.url || '') + '" style="width:40px;height:28px;object-fit:cover;border-radius:3px;flex-shrink:0">';
                        html += '<input type="text" placeholder="Link URL" value="' + (img.link || '') + '" style="flex:1;height:24px;padding:0 8px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;background:'+ImpC.panel+';color:'+ImpC.text+'">';
                        html += '<button type="button" class="impulse-remove-carousel-image" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="images" value=\'' + JSON.stringify(images).replace(/'/g, '&#39;') + '\'>';

                    var _imgMode = settings.animation_mode || 'scroll';
                    var _imgDir  = settings.direction || 'left';
                    var _objFit  = settings.object_fit || 'cover';

                    

                    
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="animation_mode" style="margin-top:5px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px">';
                    [
                        ['coverflow','Coverflow']
                        
                    ].forEach(function(m) {
                        html += '<button type="button" class="' + (_imgMode === m[0] ? 'active' : '') + '" data-value="' + m[0] + '" style="height:26px;font-size:11px;box-sizing:border-box">' + m[1] + '</button>';
                    });
                    html += '<input type="hidden" name="animation_mode" value="' + _imgMode + '">';
                    html += '</div>';

                    
                    var _imgHasDir = ['scroll','orbit','table'].indexOf(_imgMode) !== -1;
                    html += '<div style="display:flex;gap:4px;margin-top:5px;align-items:center">';
                    if (_imgHasDir) {
                    html += '<div class="impulse-btn-group" data-name="direction" style="display:flex;gap:3px">';
                    html += '<button type="button" class="' + (_imgDir === 'left' ? 'active' : '') + '" data-value="left" title="Scroll left" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg></button>';
                    html += '<button type="button" class="' + (_imgDir === 'right' ? 'active' : '') + '" data-value="right" title="Scroll right" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg></button>';
                    html += '<input type="hidden" name="direction" value="' + _imgDir + '">';
                    html += '</div>';
                    }
                    html += '<div class="impulse-btn-group" data-name="object_fit" style="display:flex;gap:3px">';
                    html += '<button type="button" class="' + (_objFit === 'cover' ? 'active' : '') + '" data-value="cover" style="height:26px;font-size:11px;padding:0 8px">Cover</button>';
                    html += '<button type="button" class="' + (_objFit === 'contain' ? 'active' : '') + '" data-value="contain" style="height:26px;font-size:11px;padding:0 8px">Contain</button>';
                    html += '<input type="hidden" name="object_fit" value="' + _objFit + '">';
                    html += '</div>';
                    html += '<div style="margin-left:auto">' + settingColorSwatchOnly('bg_color', settings.bg_color || '') + '</div>';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 12px;margin-top:5px">';
                    html += '<label class="impulse-cb-left"><input type="checkbox" name="pause_hover"' + (settings.pause_hover !== false ? ' checked' : '') + '><span>Pause on Hover</span></label>';
                    html += '<label class="impulse-cb-right"><span>Autoplay</span><input type="checkbox" name="autoplay"' + (settings.autoplay !== false ? ' checked' : '') + '></label>';
                    html += '</div>';

                    var _multiItemEffect = ['scroll','orbit','table'].indexOf(_imgMode) !== -1;

                    html += '<div class="impulse-margin-grid" style="margin-top:5px">';
                    if (_imgMode === 'scroll') {
                        html += settingSliderR('scroll_speed', 'Speed', settings, 3, 1, 10, '', false);
                    }
                    html += settingSliderR('autoplay_speed', 'Delay', settings, 4, 1, 15, 's', false);
                    if (_multiItemEffect) {
                        html += settingSliderR('items_to_show', 'Visible', settings, 1, 1, 8, '', true);
                        html += settingSliderR('gap', 'Gap', settings, 0, 0, 60, 'px', true);
                    }

                    
                    if (['orbit','table','cube'].indexOf(_imgMode) !== -1) {
                        html += settingSliderR('tilt_sens', 'Sensitivity', settings, 5, 0, 10, '', true);
                    }
                    html += settingSliderR('height', 'Height', settings, 400, 40, 800, 'px', true);
                    html += settingSliderR('slider_width', 'Max Width', settings, 100, 10, 100, '%', true);
                    html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 30, 'px', true);
                    html += settingSliderR('margin_top', 'Margin Top', settings, 0, 0, 100, 'px', true);
                    html += settingSliderR('margin_bottom', 'Margin Bottom', settings, 0, 0, 100, 'px', true);
                    html += '</div>';

                    html += '</div>'; 

                    html += '<div class="impulse-carousel-data-section"' + (_carCt !== 'data' ? ' style="display:none"' : '') + '>';

                    var _carSlides = settings.slides || [];
                    if (typeof _carSlides === 'string') {
                        try { _carSlides = JSON.parse(_carSlides); } catch(e) { _carSlides = []; }
                    }
                    if (_carSlides.length < 1) {
                        _carSlides = [
                            { id: 'slide-1', background: '', valign: 'center' },
                            { id: 'slide-2', background: '', valign: 'center' }
                        ];
                    }
                    
                    var _carSpv = Math.max(1, parseInt(settings.items_to_show) || 1);
                    while (_carSlides.length < _carSpv) {
                        var _n = _carSlides.length + 1;
                        _carSlides.push({ id: 'slide-' + _n + '-' + Date.now(), background: '', valign: 'center' });
                    }

                    var _carCurrentSlide = parseInt(settings.current_slide) || 0;
                    if (_carCurrentSlide >= _carSlides.length) _carCurrentSlide = _carSlides.length - 1;

                    
                    html += '<div class="impulse-new-slider-nav" style="display:flex;gap:3px;flex:1;min-width:0;flex-wrap:wrap">';
                    for (var _csi = 0; _csi < _carSlides.length; _csi++) {
                        var _csActive = _csi === _carCurrentSlide;
                        var _csBg = (_carSlides[_csi] && _carSlides[_csi].background) ? _carSlides[_csi].background : '';
                        var _csBtnStyle = 'width:26px;height:26px;border-radius:3px;cursor:grab;font-size:11px;box-sizing:border-box;flex-shrink:0;';
                        _csBtnStyle += _csActive ? 'background:' + (_csBg || ''+ImpC.text+'') + ';color:' + (_csBg ? ''+ImpC.white+'' : ''+ImpC.surface2+'') + ';border:none;font-weight:600;' : 'background:' + (_csBg || ''+ImpC.panel+'') + ';color:' + (_csBg ? ''+ImpC.white+'' : ''+ImpC.muted+'') + ';border:1px solid '+ImpC.border+';';
                        html += '<button type="button" class="impulse-new-slide-btn' + (_csActive ? ' active' : '') + '" draggable="true" data-index="' + _csi + '" style="' + _csBtnStyle + '">' + (_csi + 1) + '</button>';
                    }
                    html += '</div>';

                    html += '<input type="hidden" name="slides" value=\'' + JSON.stringify(_carSlides).replace(/'/g, '&#39;') + '\'>';
                    html += '<input type="hidden" name="current_slide" value="' + _carCurrentSlide + '">';

                    var _carCs = _carSlides[_carCurrentSlide] || {};
                    html += '<div class="impulse-section-divider" style="margin-top:8px">Slide ' + (_carCurrentSlide + 1) + '</div>';

                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="slide_valign" style="margin-top:6px">';
                    html += '<button type="button" class="' + ((_carCs.valign || 'center') === 'top' ? 'active' : '') + '" data-value="top">Top</button>';
                    html += '<button type="button" class="' + ((_carCs.valign || 'center') === 'center' ? 'active' : '') + '" data-value="center">Center</button>';
                    html += '<button type="button" class="' + ((_carCs.valign || 'center') === 'bottom' ? 'active' : '') + '" data-value="bottom">Bottom</button>';
                    html += '<input type="hidden" name="slide_valign" value="' + (_carCs.valign || 'center') + '">';
                    html += '</div>';

                    html += '<div style="display:flex;gap:16px;align-items:flex-start;margin-top:10px">';
                    html += '<div style="display:flex;flex-direction:column;gap:4px;align-items:flex-start">';
                    html += '<label style="font-size:11px;color:#888;margin:0">Background</label>';
                    html += settingColorSwatchOnly('slide_bg_color', _carCs.background || '');
                    html += '</div>';
                    html += '<div style="display:flex;flex-direction:column;gap:4px;align-items:flex-end;margin-left:auto">';
                    html += '<label style="font-size:11px;color:#888;margin:0">Autoplay</label>';
                    html += '<input type="checkbox" name="autoplay"' + (settings.autoplay !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px;cursor:pointer">';
                    html += '</div>';
                    html += '</div>';

                    
                    var _carEff = settings.slider_effect || 'slide';
                    var _carEffects = [
                        'slide'
                        
                    ];
                    var _carEffLabels = { slide:'Slide', scroll:'Scroll', coverflow:'Coverflow', cube:'Cube', conveyor:'Conveyor', portal:'Portal', depth_rush:'Depth', card_flip:'Flip' };
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="slider_effect" style="margin-top:10px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px">';
                    _carEffects.forEach(function(ef) {
                        html += '<button type="button" class="' + (_carEff === ef ? 'active' : '') + '" data-value="' + ef + '" style="height:26px;font-size:11px;box-sizing:border-box">' + _carEffLabels[ef] + '</button>';
                    });
                    html += '<input type="hidden" name="slider_effect" value="' + _carEff + '">';
                    html += '</div>';

                    var _carDir = settings.direction || 'right';
                    if (_carEff === 'slide') {
                    html += '<div class="impulse-inline-right" style="margin-top:10px">';
                    html += '<label style="font-size:11px">Direction</label>';
                    html += '<div class="impulse-btn-group" data-name="direction" style="display:flex;gap:3px">';
                    html += '<button type="button" class="' + (_carDir === 'left' ? 'active' : '') + '" data-value="left" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg></button>';
                    html += '<button type="button" class="' + (_carDir === 'right' ? 'active' : '') + '" data-value="right" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg></button>';
                    html += '<button type="button" class="' + (_carDir === 'up' ? 'active' : '') + '" data-value="up" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 15 12 9 6 15"/></svg></button>';
                    html += '<button type="button" class="' + (_carDir === 'down' ? 'active' : '') + '" data-value="down" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></button>';
                    html += '<input type="hidden" name="direction" value="' + _carDir + '">';
                    html += '</div>';
                    html += '</div>';
                    } 

                    html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                    html += settingSliderR('height', 'Height', settings, 500, 100, 900, 'px', true);
                    html += settingSliderR('slider_width', 'Max Width', settings, 1200, 200, 1600, 'px', true);
                    html += settingSliderR('items_to_show', 'Visible', settings, 1, 1, 6, '', true);
                    html += settingSliderR('gap', 'Gap', settings, 0, 0, 60, 'px', true);
                    html += settingSliderR('transition_speed', 'Transition', settings, 400, 100, 2000, 'ms');
                    html += settingSliderR('autoplay_speed', 'Delay', settings, 5, 1, 15, 's');

                    if (_carEff === 'cube') {
                        html += settingSliderR('tilt_sens', 'Sensitivity', settings, 5, 0, 10, '', true);
                    }
                    html += '</div>';

                    html += '</div>'; 
                    break;
                
                case 'slider':
                    
                    var slides = settings.slides || [];
                    if (typeof slides === 'string') {
                        try { slides = JSON.parse(slides); } catch(e) { slides = []; }
                    }
                    while (slides.length < 3) {
                        slides.push({ id: 'slide-' + (slides.length + 1), background: '', valign: 'center' });
                    }
                    slides = slides.slice(0, 3);

                    var currentSlide = parseInt(settings.current_slide) || 0;
                    if (currentSlide >= 3) currentSlide = 2;

                    html += '<div style="display:flex;justify-content:space-between;align-items:center">';

                    html += '<div class="impulse-new-slider-nav" style="display:flex;gap:3px;align-items:center">';
                    for (var i = 0; i < 3; i++) {
                        var isSelected = i === currentSlide;
                        var btnStyle = 'width:26px;height:26px;border-radius:3px;cursor:pointer;font-size:11px;box-sizing:border-box;';
                        btnStyle += isSelected ? 'background:'+ImpC.text+';color:'+ImpC.surface2+';border:1px solid '+ImpC.border+';font-weight:600;' : 'background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';';
                        html += '<button type="button" class="impulse-new-slide-btn' + (isSelected ? ' active' : '') + '" draggable="true" data-index="' + i + '" style="' + btnStyle + 'cursor:grab">' + (i + 1) + '</button>';
                    }
                    html += '</div>';
                    html += '<input type="hidden" name="slide_count" value="3">';

                    var dir = settings.direction || 'right';
                    html += '<div class="impulse-btn-group" data-name="direction" style="display:flex;gap:3px">';
                    html += '<button type="button" class="' + (dir === 'left' ? 'active' : '') + '" data-value="left" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 15h-6v4l-7-7 7-7v4h6v6z"/></svg></button>';
                    html += '<button type="button" class="' + (dir === 'right' ? 'active' : '') + '" data-value="right" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9h6V5l7 7-7 7v-4H6V9z"/></svg></button>';
                    html += '<button type="button" class="' + (dir === 'up' ? 'active' : '') + '" data-value="up" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18v-6H5l7-7 7 7h-4v6H9z"/></svg></button>';
                    html += '<button type="button" class="' + (dir === 'down' ? 'active' : '') + '" data-value="down" style="width:26px;height:26px;padding:0;box-sizing:border-box"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 6v6h4l-7 7-7-7h4V6h6z"/></svg></button>';
                    html += '<input type="hidden" name="direction" value="' + dir + '">';
                    html += '</div>';
                    html += '</div>';

                    html += '<input type="hidden" name="slides" value=\'' + JSON.stringify(slides).replace(/'/g, '&#39;') + '\'>';
                    html += '<input type="hidden" name="current_slide" value="' + currentSlide + '">';

                    var cs = slides[currentSlide] || {};
                    html += '<div class="impulse-section-divider" style="margin-top:8px">Slide ' + (currentSlide + 1) + '</div>';

                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="slide_valign" style="margin-top:6px">';
                    html += '<button type="button" class="' + ((cs.valign || 'center') === 'top' ? 'active' : '') + '" data-value="top">Top</button>';
                    html += '<button type="button" class="' + ((cs.valign || 'center') === 'center' ? 'active' : '') + '" data-value="center">Center</button>';
                    html += '<button type="button" class="' + ((cs.valign || 'center') === 'bottom' ? 'active' : '') + '" data-value="bottom">Bottom</button>';
                    html += '<input type="hidden" name="slide_valign" value="' + (cs.valign || 'center') + '">';
                    html += '</div>';

                    html += '<div style="display:flex;gap:16px;align-items:flex-start;margin-top:10px">';
                    
                    html += '<div style="display:flex;flex-direction:column;gap:4px;align-items:flex-start">';
                    html += '<label style="font-size:11px;color:#888;margin:0">Background</label>';
                    html += settingColorSwatchOnly('slide_bg_color', cs.background || '');
                    html += '</div>';
                    
                    html += '<div style="display:flex;flex-direction:column;gap:4px;align-items:flex-end;margin-left:auto">';
                    html += '<label style="font-size:11px;color:#888;margin:0">Autoplay</label>';
                    html += '<input type="checkbox" name="autoplay"' + (settings.autoplay ? ' checked' : '') + ' style="margin:0;width:14px;height:14px;cursor:pointer">';
                    html += '</div>';
                    html += '</div>';

                    var slEff = settings.slider_effect || 'slide';
                    var sliderEffects = [
                        'slide'
                        
                    ];
                    var sliderEffectLabels = { slide:'Slide', scroll:'Scroll', coverflow:'Coverflow', cube:'Cube', conveyor:'Conveyor', portal:'Portal', depth_rush:'Depth', card_flip:'Flip' };
                    html += '<div class="impulse-btn-group impulse-btn-group-full" data-name="slider_effect" style="margin-top:10px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:3px">';
                    sliderEffects.forEach(function(ef) {
                        html += '<button type="button" class="' + (slEff === ef ? 'active' : '') + '" data-value="' + ef + '" style="height:26px;font-size:11px;box-sizing:border-box">' + sliderEffectLabels[ef] + '</button>';
                    });
                    html += '<input type="hidden" name="slider_effect" value="' + slEff + '">';
                    html += '</div>';

                    var _hm = settings.height_mode || 'fixed';
                    html += '<div class="impulse-inline-right" style="margin-top:10px">';
                    html += '<label style="font-size:11px">Height</label>';
                    html += '<div class="impulse-btn-group" data-name="height_mode" style="display:flex;gap:3px">';
                    html += '<button type="button" data-value="fixed" class="' + (_hm === 'fixed' ? 'active' : '') + '" style="height:26px;font-size:11px;padding:0 10px">Fixed</button>';
                    html += '<button type="button" data-value="auto" class="' + (_hm === 'auto' ? 'active' : '') + '" style="height:26px;font-size:11px;padding:0 10px">Auto</button>';
                    html += '<input type="hidden" name="height_mode" value="' + _hm + '">';
                    html += '</div>';
                    html += '</div>';
                    
                    html += '<div class="impulse-slider-height-settings' + (_hm === 'auto' ? ' is-auto-height' : '') + '" style="' + (_hm === 'auto' ? 'opacity:0.45;pointer-events:none;' : '') + '">';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('height', 'Min Height', settings, 500, 200, 900, 'px');
                    html += settingSliderR('slider_width', 'Width', settings, 1200, 200, 1600, 'px');
                    html += '</div></div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:6px">';
                    html += settingSliderR('transition_speed', 'Duration', settings, 400, 100, 2000, 'ms');
                    html += settingSliderR('autoplay_speed', 'Interval', settings, 5, 1, 15, 's');
                    html += '</div>';
                    html += settingBgShapes(settings);
                    break;

                case 'configurator':

                    
                    
                    html += (window.ImpulseConfigurator ? window.ImpulseConfigurator.buildManager(settings) : '');
                    break;

                case 'products':
                case 'products':
                    html += buildCardDesignSettings(settings, false, '', true, null);
                    break;
                
                case 'bundle':
                    
                    var bundleId = settings.bundle_id || 0;
                    var bundleLabel = settings.bundle_label || 'Select a bundle…';
                    html += '<div style="display:flex;gap:4px;margin-bottom:8px">';
                    html += '<button type="button" id="pb-pick-bundle-btn" style="flex:1;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:' + (bundleId ? ''+ImpC.text+'' : '#666') + ';font-size:11px;cursor:pointer;text-align:left;padding:0 8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + $('<s>').text(bundleLabel).html() + '</button>';
                    if (bundleId) {
                        html += '<button type="button" id="pb-clear-bundle-btn" style="width:26px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:#666;font-size:14px;cursor:pointer">&times;</button>';
                    }
                    html += '</div>';
                    html += '<input type="hidden" name="bundle_id" value="' + bundleId + '">';
                    html += '<input type="hidden" name="bundle_label" value="' + $('<s>').text(settings.bundle_label || '').html() + '">';

                    html += '<div class="impulse-inline-right" style="margin-bottom:8px">';
                    html += '<label style="font-size:11px">Button</label>';
                    html += '<input type="text" name="btn_label" value="' + ($('<s>').text(settings.btn_label || 'Add Bundle to Cart').html()) + '" placeholder="Add Bundle to Cart" style="width:130px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;padding:0 8px;box-sizing:border-box">';
                    html += '</div>';

                    html += '<div style="display:flex;justify-content:space-between;margin-bottom:10px">';
                    html += '<label style="display:flex;align-items:center;gap:5px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_images"' + (settings.show_images !== false ? ' checked' : '') + ' style="margin:0">Images</label>';
                    html += '<label style="display:flex;align-items:center;gap:5px;font-size:11px;color:'+ImpC.muted+';cursor:pointer">Prices<input type="checkbox" name="show_prices"' + (settings.show_prices !== false ? ' checked' : '') + ' style="margin:0"></label>';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">';
                    html += '<div>' + settingColorSwatch('accent_color', 'Accent', settings.accent_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="text-align:right"><div style="font-size:11px;color:#888;margin-bottom:4px">Fields</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('field_color', settings.field_color || ''+ImpC.light+'') + '</div></div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('bundle_width', 'Max Width', settings, 400, 340, 600, 'px');
                    html += settingSliderR('border_radius', 'Radius', settings, 4, 0, 10, 'px');
                    html += '</div>';
                    break;

                
                case 'cart':
                    
                    var cartMode = settings.cart_mode || 'full';
                    if (cartMode === 'icon') cartMode = 'full'; 
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="cart_mode" style="display:flex;width:100%;gap:3px">';
                    [{v:'full',l:'Full'},{v:'mini',l:'Mini'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (cartMode === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="cart_mode" value="' + cartMode + '">';
                    html += '</div>';

                    html += '<div class="impulse-cart-mini-settings" style="' + (cartMode !== 'mini' ? 'display:none' : '') + '">';
                    html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="align" style="display:flex;width:100%;gap:3px;margin-top:6px">';
                    [{v:'left',l:'Left'},{v:'center',l:'Center'},{v:'right',l:'Right'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + ((settings.align || 'center') === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="align" value="' + (settings.align || 'center') + '">';
                    html += '</div>';
                    html += '<div class="impulse-inline-right" style="margin-top:12px"><label style="font-size:11px">Title</label><input type="text" name="title" value="' + escapeHtml(settings.title || 'Your Cart') + '" style="width:155px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:6px"><label style="font-size:11px">Empty</label><input type="text" name="empty_text" value="' + escapeHtml(settings.empty_text || 'Your cart is empty') + '" style="width:155px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:6px"><label style="font-size:11px">Button</label><input type="text" name="button_text" value="' + escapeHtml(settings.button_text || 'Checkout') + '" style="width:155px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:12px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_subtotal"' + (settings.show_subtotal !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Subtotal</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer">Remove btn <input type="checkbox" name="show_remove"' + (settings.show_remove !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '</div>';
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="hide_when_empty"' + (settings.hide_when_empty !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Hide if empty</label>';
                    html += '</div>';
                    html += '<div class="impulse-card-row-double" style="margin-top:12px">';
                    html += settingColorSwatch('bg_color', 'Background', settings.bg_color || '#ffffff', true, true);
                    html += settingColorSwatch('text_color', 'Text', settings.text_color || ''+ImpC.surface2+'', true, false);
                    html += '</div>';
                    html += '<div class="impulse-card-row-double">';
                    html += settingColorSwatch('button_bg', 'Button BG', settings.button_bg || ''+ImpC.surface2+'', true, true);
                    html += settingColorSwatch('button_color', 'Button Text', settings.button_color || '#ffffff', true, false);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('width', 'Width', settings, 320, 280, 480, 'px', true);
                    html += settingSliderR('border_radius', 'Radius', settings, 0, 0, 24, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('image_size', 'Image', settings, 60, 40, 100, 'px');
                    html += settingSliderR('button_size', 'Btn size', settings, 14, 12, 18, 'px');
                    html += '</div>';
                    html += '</div>';

                    html += '<div class="impulse-cart-full-settings" style="' + (cartMode !== 'full' ? 'display:none' : '') + '">';
                    html += '<div class="impulse-inline-right" style="margin-top:6px"><label style="font-size:11px">Title</label><input type="text" name="title" value="' + escapeHtml(settings.title || 'Your Order') + '" style="width:155px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:6px"><label style="font-size:11px">Empty</label><input type="text" name="empty_text" value="' + escapeHtml(settings.empty_text || 'Your cart is empty') + '" style="width:155px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    
                    var _cartDevice = window.impulseDevice || 'desktop';
                    var _cartRaw = $('.impulse-panel-right').data('existing-settings') || {};
                    function _cartChk(name) {
                        if (_cartDevice === 'mobile' && _cartRaw[name + '_mobile'] === undefined) return false;
                        if (_cartDevice === 'tablet' && _cartRaw[name + '_tablet'] === undefined && _cartDevice === 'tablet') return settings[name] !== false;
                        return settings[name] !== false;
                    }
                    html += '<div class="impulse-setting-row" data-responsive="true" style="display:flex;justify-content:space-between;align-items:center;margin-top:12px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+'"><input type="checkbox" name="show_image"' + (_cartChk('show_image') ? ' checked' : '') + ' style="margin:0;accent-color:#666"> Images</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+'">Quantity <input type="checkbox" name="show_quantity"' + (_cartChk('show_quantity') ? ' checked' : '') + ' style="margin:0;accent-color:#666"></label>';
                    html += '</div>';
                    html += '<div class="impulse-setting-row" data-responsive="true" style="display:flex;justify-content:space-between;align-items:center;margin-top:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+'"><input type="checkbox" name="show_subtotal"' + (_cartChk('show_subtotal') ? ' checked' : '') + ' style="margin:0;accent-color:#666"> Subtotals</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+'">Header <input type="checkbox" name="show_header"' + (_cartChk('show_header') ? ' checked' : '') + ' style="margin:0;accent-color:#666"></label>';
                    html += '</div>';
                    html += '<div class="impulse-setting-row" data-responsive="true" style="display:flex;justify-content:space-between;align-items:center;margin-top:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+'"><input type="checkbox" name="show_table"' + (_cartChk('show_table') ? ' checked' : '') + ' style="margin:0;accent-color:#666"> Table labels</label>';
                    html += '</div>';

                    
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;margin-top:12px;margin-bottom:6px">';
                    html += '<div style="display:flex;flex-direction:column;align-items:flex-start;gap:4px"><span style="font-size:11px;color:#aaa">Background</span>' + settingColorSwatchOnly('bg_color', settings.bg_color || '#ffffff', 'Cart background') + '</div>';
                    html += '<div style="display:flex;flex-direction:column;align-items:center;gap:4px"><span style="font-size:11px;color:#aaa">Button</span>' + settingColorSwatchOnly('checkout_btn_bg', settings.checkout_btn_bg || ''+ImpC.surface2+'', 'Button background') + '</div>';
                    html += '<div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px"><span style="font-size:11px;color:#aaa">Text</span>' + settingColorSwatchOnly('checkout_btn_color', settings.checkout_btn_color || '#ffffff', 'Button text') + '</div>';
                    html += '</div>';
                    html += '<div class="impulse-inline-right" style="margin-bottom:6px"><label style="font-size:11px">Button label</label><input type="text" name="checkout_btn_text" value="' + escapeHtml(settings.checkout_btn_text || 'Checkout') + '" style="width:130px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('border_radius', 'Radius', settings, 4, 0, 24, 'px', true);
                    html += settingSliderR('max_width', 'Width', settings, ((window.impulseDevice || 'desktop') === 'mobile' ? 100 : 50), 30, 100, '%', true);
                    html += '</div>';
                    html += '</div>';
                    break;
                    
                case 'checkout':
                    
                    var _ckScreenMode = Impulse.pageSettings && (true);
                    var cd = {
                        preset: settings.checkout_design_preset || 'classic',
                        colors: {
                            button: settings.checkout_design_button || ''+ImpC.surface2+'',
                            button_text: settings.checkout_design_button_text || '#ffffff',
                            text: settings.checkout_design_text || (_ckScreenMode ? '#ffffff' : ''+ImpC.surface2+''),
                            form_bg: settings.checkout_design_form_bg || 'transparent',
                            field_bg: settings.checkout_design_field_bg || (_ckScreenMode ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.05)'),
                            field_border: settings.checkout_design_field_border || '#cccccc'
                        },
                        field_border_width: settings.checkout_design_field_border_width !== undefined ? settings.checkout_design_field_border_width : 1,
                        field_radius: settings.checkout_design_field_radius !== undefined ? settings.checkout_design_field_radius : 4,
                        button_radius: settings.checkout_design_button_radius !== undefined ? settings.checkout_design_button_radius : 4,
                        guest_checkout: settings.checkout_design_guest_checkout !== undefined ? settings.checkout_design_guest_checkout : true,
                        create_account: settings.checkout_design_create_account !== undefined ? settings.checkout_design_create_account : true,
                        email_first: settings.checkout_design_email_first !== undefined ? settings.checkout_design_email_first : true,
                        address_autocomplete: settings.checkout_design_address_autocomplete || false,
                        google_places_key: settings.checkout_design_google_places_key || '',
                        show_coupon: settings.checkout_design_show_coupon !== undefined ? settings.checkout_design_show_coupon : true,
                        show_gift_card: settings.checkout_design_show_gift_card !== undefined ? settings.checkout_design_show_gift_card : true,
                        fields: []
                    };

                    var fieldsJson = settings.checkout_design_fields;
                    if (typeof fieldsJson === 'string' && fieldsJson) {
                        try { cd.fields = JSON.parse(fieldsJson); } catch(e) { cd.fields = []; }
                    } else if (Array.isArray(fieldsJson)) {
                        cd.fields = fieldsJson;
                    }

                    if (!cd.fields || !cd.fields.length) {
                        cd.fields = [
                            {id: 'email', label: 'Email', enabled: true, required: true, width: 'half', locked: true},
                            {id: 'phone', label: 'Phone', enabled: true, required: false, width: 'half'},
                            {id: 'first_name', label: 'First Name', enabled: true, required: true, width: 'half'},
                            {id: 'last_name', label: 'Last Name', enabled: true, required: true, width: 'half'},
                            {id: 'company', label: 'Company', enabled: false, required: false, width: 'full'},
                            {id: 'address_1', label: 'Address', enabled: true, required: true, width: 'full'},
                            {id: 'address_2', label: 'Apt, Suite, etc.', enabled: true, required: false, width: 'full'},
                            {id: 'city', label: 'City', enabled: true, required: true, width: 'half'},
                            {id: 'state', label: 'State', enabled: true, required: true, width: 'half'},
                            {id: 'postcode', label: 'ZIP Code', enabled: true, required: true, width: 'half'},
                            {id: 'country', label: 'Country', enabled: true, required: true, width: 'half'}
                        ];
                    }

                    var _halfFields = {email:1, phone:1, first_name:1, last_name:1, city:1, state:1, postcode:1, country:1};
                    function _fieldWidth(fid) { return _halfFields[fid] ? 'half' : 'full'; }
                    
                    html += '<div class="impulse-checkout-fields-list" data-name="checkout_fields" style="margin-top:12px;display:flex;flex-direction:column;gap:3px">';
                    cd.fields.forEach(function(field, idx) {
                        var isEmail = field.id === 'email';
                        var fWidth = _fieldWidth(field.id);
                        
                        field.width = fWidth;
                        html += '<div class="impulse-checkout-field-item" data-field-id="' + field.id + '" data-index="' + idx + '"';
                        html += ' data-width="' + fWidth + '" data-required="' + (field.required || isEmail ? '1' : '0') + '" data-enabled="1"';
                        html += ' data-email="' + (isEmail ? '1' : '0') + '" draggable="true">';
                        html += '<input type="text" class="impulse-checkout-field-label" value="' + escapeHtml(field.label) + '">';
                        
                        html += '<label class="impulse-field-required-toggle" title="Required"' + (isEmail ? ' data-locked="1"' : '') + '>';
                        html += '<input type="checkbox" class="impulse-field-required-cb"' + ((field.required || isEmail) ? ' checked' : '') + (isEmail ? ' disabled' : '') + '>';
                        html += '</label>';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<button type="button" class="instinctor-btn" style="width:100%;margin-top:4px;height:26px;padding:0;font-size:11px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';color:'+ImpC.muted+'" id="impulse-add-checkout-field">';
                    html += '<svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" fill="none" stroke-width="2" style="margin-right:4px;vertical-align:-1px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>';
                    html += 'Add Custom Field</button>';
                    html += '<input type="hidden" name="checkout_design_fields" value="' + escapeHtml(JSON.stringify(cd.fields)) + '">';

                    html += '<div class="impulse-inline-right" style="margin-top:8px"><label style="font-size:11px">Button Text</label><input type="text" name="checkout_button_text" value="' + escapeHtml(settings.checkout_button_text || 'Pay now') + '" style="width:120px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';

                    html += '<input type="hidden" name="checkout_design_preset" value="classic">';

                    
                    
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-top:12px">';
                    html += '<div style="text-align:left">' + settingColorSwatch('checkout_design_button', 'Button', cd.colors.button) + '</div>';
                    html += '<div style="text-align:center">' + settingColorSwatch('checkout_design_text', 'Labels', cd.colors.text) + '</div>';
                    html += '<div style="text-align:right">' + settingColorSwatch('checkout_design_field_bg', 'Fields', cd.colors.field_bg) + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('checkout_design_field_radius', 'Radius', settings, 4, 0, 20, 'px', true);
                    html += settingSliderR('section_max_width', 'Max Width', settings, 400, 400, 1200, 'px', true);
                    html += '</div>';
                    if (!_ckScreenMode) {
                        html += '<div class="impulse-margin-grid">';
                        html += settingSliderR('checkout_design_field_border_width', 'Border Width', settings, 1, 0, 3, 'px', true);
                        html += '</div>';
                    }
                    break;
                
                case 'shape':

                    
                    break;

                case 'contact':
                    
                    var fields = settings.fields;
                    if (typeof fields === 'string') {
                        try { fields = JSON.parse(fields); } catch(e) { fields = null; }
                    }
                    if (!fields || !Array.isArray(fields) || fields.length === 0) {
                        fields = [
                            {type: 'text', label: 'Your Name', name: 'name', placeholder: '', required: true, width: 'full'},
                            {type: 'email', label: 'Email Address', name: 'email', placeholder: '', required: true, width: 'full'},
                            {type: 'textarea', label: 'Message', name: 'message', placeholder: '', required: false, width: 'full'}
                        ];
                    }

                    
                    var _formTypes = [{v:'text',l:'Text'},{v:'email',l:'Email'},{v:'phone',l:'Phone'},{v:'number',l:'Number'},{v:'date',l:'Date'},{v:'time',l:'Time'},{v:'textarea',l:'Textarea'},{v:'select',l:'Dropdown'},{v:'checkbox',l:'Checkbox'}];
                    html += '<div class="impulse-form-fields-list" data-name="form_fields" style="display:flex;flex-direction:column;gap:5px">';

                    

                    
                    fields.forEach(function(field, idx) {
                        var fType = field.type || 'text';
                        var fWidth = field.width !== undefined ? field.width : 'full';
                        var fOptions = field.options !== undefined ? String(field.options) : '';

                        

                        
                        
                        html += '<div class="impulse-form-field-item" data-field-type="' + fType + '" data-index="' + idx + '"';
                        html += ' data-required="' + (field.required ? '1' : '0') + '" data-enabled="1"';
                        html += ' data-width="' + escapeHtml(String(fWidth)) + '"';
                        html += ' data-options="' + escapeHtml(fOptions) + '"';
                        html += ' data-name="' + escapeHtml(field.name || '') + '" data-placeholder="' + escapeHtml(field.placeholder || '') + '" draggable="true"';
                        html += ' style="flex-wrap:wrap">';

                        

                        html += '<div class="impulse-form-field-row" style="flex:0 0 100%;display:flex;align-items:center;gap:3px;width:100%;min-width:0">';

                        
                        
                        html += '<span class="impulse-form-field-typewrap" title="Field type" style="position:relative;width:28px;height:26px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;border:1px solid '+ImpC.border+';border-radius:3px;background:'+ImpC.panel+';color:'+ImpC.muted+'">';
                        html += '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" style="pointer-events:none"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>';
                        html += '<select class="impulse-form-field-type-select" title="Field type" style="position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;border:0;padding:0;margin:0">';
                        _formTypes.forEach(function(t) {
                            html += '<option value="' + t.v + '"' + (fType === t.v ? ' selected' : '') + '>' + t.l + '</option>';
                        });
                        html += '</select>';
                        html += '</span>';
                        html += '<input type="text" class="impulse-form-field-label" value="' + escapeHtml(field.label || 'Field') + '" style="flex:1 1 auto;min-width:0;height:26px">';

                        
                        
                        var _isHalfW = String(fWidth) === '50' || String(fWidth).toLowerCase() === 'half';
                        var _isReq   = !!field.required;

                        

                        

                        
                        
                        var _rowBase = 'display:flex;align-items:center;gap:3px;cursor:pointer;height:12px;user-select:none;flex-shrink:0';
                        var _cbOff   = 'display:inline-block;width:12px;height:12px;border:1px solid #555;border-radius:2px;flex-shrink:0;background:transparent;box-sizing:border-box';
                        var _cbOn    = 'display:inline-block;width:12px;height:12px;border:1px solid #ffffff;border-radius:2px;flex-shrink:0;background:#ffffff;box-sizing:border-box';
                        var _halfLbl = 'font-size:10px;font-weight:600;line-height:1;color:' + ImpC.muted;
                        var _reqLbl  = 'font-size:16px;font-weight:700;line-height:0;color:' + ImpC.muted + ';position:relative;top:2px';

                        

                        
                        html += '<div class="impulse-form-field-toggles" style="display:flex;flex-direction:column;gap:2px;flex-shrink:0">';
                        html += '<label class="impulse-field-width-toggle" title="Half width (50%)" style="' + _rowBase + '">';
                        html += '<input type="checkbox" class="impulse-field-half-cb impulse-cb-hidden" style="display:none"' + (_isHalfW ? ' checked' : '') + '>';
                        html += '<span class="impulse-field-cb-square" style="' + (_isHalfW ? _cbOn : _cbOff) + '"></span>';
                        html += '<span style="' + _halfLbl + '">½</span>';
                        html += '</label>';
                        html += '<label class="impulse-field-required-toggle" title="Required" style="' + _rowBase + '">';
                        html += '<input type="checkbox" class="impulse-field-required-cb impulse-cb-hidden" style="display:none"' + (_isReq ? ' checked' : '') + '>';
                        html += '<span class="impulse-field-cb-square" style="' + (_isReq ? _cbOn : _cbOff) + '"></span>';
                        html += '<span style="' + _reqLbl + '">*</span>';
                        html += '</label>';
                        html += '</div>';

                        html += '<button type="button" class="impulse-form-field-delete" title="Remove field" style="width:22px;height:22px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;margin-left:2px"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>'; 

                        var _optsShow = (fType === 'select') ? 'block' : 'none';
                        html += '<textarea class="impulse-form-field-options" placeholder="One option per line" style="display:' + _optsShow + ';flex:0 0 100%;width:100%;margin-top:4px;min-height:60px;padding:6px 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;resize:vertical;font-family:inherit;line-height:1.4">' + escapeHtml(fOptions) + '</textarea>';
                        html += '</div>';
                    });
                    html += '</div>';

                    html += '<button type="button" class="instinctor-btn" style="width:100%;margin-top:8px" id="impulse-add-form-field">';
                    html += '<svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" fill="none" stroke-width="2" style="margin-right:4px;vertical-align:-1px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>';
                    html += 'Add Field</button>';

                    html += '<input type="hidden" name="fields" value="' + escapeHtml(JSON.stringify(fields)) + '">';

                    

                    

                    

                    

                    var _lblAbs = 'position:absolute;bottom:100%;margin-bottom:4px;white-space:nowrap;font-size:11px;color:#aaa';
                    html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-top:24px">';
                    html += '<div style="position:relative"><span style="' + _lblAbs + ';left:0">Button</span>' + settingColorSwatchOnly('button_bg', settings.button_bg || ''+ImpC.surface+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbs + ';left:50%;transform:translateX(-50%)">Fields</span>' + settingColorSwatchOnly('field_bg', settings.field_bg || '#ffffff') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbs + ';left:50%;transform:translateX(-50%)">Border</span>' + settingColorSwatchOnly('field_border_color', settings.field_border_color || ''+ImpC.text+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbs + ';left:50%;transform:translateX(-50%)">Text</span>' + settingColorSwatchOnly('field_text_color', settings.field_text_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbs + ';right:0">Label</span>' + settingColorSwatchOnly('field_label_color', settings.field_label_color || '') + '</div>';
                    html += '</div>';

                    var inputStyle = 'width:100%;height:26px;margin-top:6px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box';
                    html += '<div style="margin-top:12px">';
                    html += '<div class="impulse-btn-group" data-name="on_submit" style="display:flex;width:100%">';
                    [{v:'message',l:'Show Message'},{v:'redirect',l:'Redirect'}].forEach(function(o) {
                        var active = (settings.on_submit || 'message') === o.v ? ' class="active"' : '';
                        html += '<button type="button" data-value="' + o.v + '"' + active + ' style="flex:1">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="on_submit" value="' + (settings.on_submit || 'message') + '">';
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="impulse-form-message-settings" style="display:' + (settings.on_submit === 'redirect' ? 'none' : 'block') + '">';
                    html += '<input type="text" name="success_message" value="' + escapeHtml(settings.success_message || 'Thank you!') + '" placeholder="Success message" style="' + inputStyle + '">';
                    html += '</div>';
                    html += '<div class="impulse-form-redirect-settings" style="display:' + (settings.on_submit === 'redirect' ? 'block' : 'none') + '">';
                    html += '<input type="text" name="redirect_url" value="' + escapeHtml(settings.redirect_url || '') + '" placeholder="Redirect URL" style="' + inputStyle + '">';
                    html += '</div>';

                    html += '<input type="text" name="button_text" value="' + escapeHtml(settings.button_text || 'Send Message') + '" placeholder="Button text" style="' + inputStyle + '">';

                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('field_radius', 'Radius', settings, 4, 0, 20, 'px', true);
                    html += settingSliderR('section_max_width', 'Max Width', settings, 400, 200, 900, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('field_gap', 'Field Gap', settings, 16, 3, 20, 'px', true);
                    html += settingSliderR('button_width', 'Button Width', settings, 100, 20, 100, '%', true);
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    break;
                
                case 'network':
                    var netCards = settings.cards;
                    if (typeof netCards === 'string') { try { netCards = JSON.parse(netCards); } catch(e) { netCards = null; } }
                    if (!Array.isArray(netCards) || !netCards.length) {
                        netCards = [
                            {id:'google',icon:'search',label:'Google',desc:'Built-in SEO so you show up when people search.',link:'',col:0,row:0},
                            {id:'ordering',icon:'shopping-bag',label:'Ordering',desc:'Commission-free online ordering on your own domain.',link:'',col:2,row:0},
                            {id:'menu',icon:'clipboard-list',label:'Menu',desc:'A live menu that updates everywhere at once.',link:'',col:3,row:0},
                            {id:'payments',icon:'credit-card',label:'Payments',desc:'Take card and digital payments right on your site.',link:'',col:1,row:1},
                            {id:'data',icon:'database',label:'Data',desc:'Every order and customer in one place you own.',link:'',col:2,row:1}
                        ];
                    }

                    
                    
                    var netRtDev = window.impulseDevice || 'desktop';
                    var netRtKey = netRtDev === 'desktop' ? 'routes' : 'routes_' + netRtDev;
                    var netRtInherited = false;
                    var netRoutes = settings[netRtKey];
                    if (netRoutes == null || netRoutes === '' || (typeof netRoutes === 'string' && netRoutes === '[]')) {
                        netRoutes = settings.routes;
                        netRtInherited = (netRtDev !== 'desktop');
                    }
                    if (typeof netRoutes === 'string') { try { netRoutes = JSON.parse(netRoutes); } catch(e) { netRoutes = null; } }
                    if (!Array.isArray(netRoutes)) { netRoutes = [['google','ordering','data'],['google','payments','data','menu']]; }

                    
                    var _ncols = String(getResponsiveValue(settings, 'cols', 4));
                    var _nrows = String(getResponsiveValue(settings, 'rows', 2));
                    html += '<div class="impulse-inline-right" style="margin-top:2px">';
                    html += '<label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Columns</label>';
                    html += '<div class="impulse-btn-group" data-name="cols" style="display:flex;gap:3px">';
                    ['1','2','3','4','5','6'].forEach(function (v) { html += '<button type="button" data-value="' + v + '" class="' + (_ncols === v ? 'active' : '') + '" style="width:26px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + v + '</button>'; });
                    html += '<input type="hidden" name="cols" value="' + _ncols + '">';
                    html += '</div></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:6px">';
                    html += '<label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Rows</label>';
                    html += '<div class="impulse-btn-group" data-name="rows" style="display:flex;gap:3px">';
                    ['1','2','3','4','5','6'].forEach(function (v) { html += '<button type="button" data-value="' + v + '" class="' + (_nrows === v ? 'active' : '') + '" style="width:26px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + v + '</button>'; });
                    html += '<input type="hidden" name="rows" value="' + _nrows + '">';
                    html += '</div></div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    html += settingSliderR('gap', 'Gap', settings, 16, 0, 48, 'px', true);
                    html += settingSliderR('cell_size', 'Card Size', settings, 84, 48, 160, 'px', true);
                    html += settingSliderR('travel_speed', 'Trace Speed', settings, 300, 80, 800, '', true);
                    html += settingSliderR('rotation_speed', 'Fill Spin', settings, 5, 1, 20, 's', true);
                    html += settingSliderR('reveal_hold', 'Start Delay', settings, 1800, 0, 3000, 'ms', true);
                    html += '</div>';

                    html += '<div class="impulse-btn-group" data-name="idle" style="display:flex;width:100%;margin-top:8px">';
                    [{v:'cycle',l:'Auto-cycle'},{v:'static',l:'Until hover'}].forEach(function(o) {
                        var a = (settings.idle || 'cycle') === o.v ? ' class="active"' : '';
                        html += '<button type="button" data-value="' + o.v + '"' + a + ' style="flex:1">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="idle" value="' + (settings.idle || 'cycle') + '">';
                    html += '</div>';

                    html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:0 4px;margin-top:10px">';
                    html += '<div>' + settingColorSwatchOnly('color1', settings.color1 || '#22d3ee') + '</div>';
                    html += '<div>' + settingColorSwatchOnly('color2', settings.color2 || '#3b82f6') + '</div>';
                    html += '<div>' + settingColorSwatchOnly('color3', settings.color3 || '#8b5cf6') + '</div>';
                    html += '<div>' + settingColorSwatchOnly('color4', settings.color4 || '#d946ef') + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-section-divider" style="margin-top:12px">Cards</div>';
                    html += '<div style="font-size:10px;color:' + ImpC.muted + ';margin:0 0 6px;line-height:1.4">Drag cards on the preview to place them.</div>';
                    html += '<div class="impulse-net-cards-list" style="display:flex;flex-direction:column;gap:6px">';
                    netCards.forEach(function(c) { html += impulseNetCardRow(c); });
                    html += '</div>';
                    html += '<button type="button" class="instinctor-btn" id="impulse-add-net-card" style="width:100%;margin-top:8px">+ Add card</button>';
                    html += '<input type="hidden" name="cards" value="' + escapeHtml(JSON.stringify(netCards)) + '">';

                    html += '<div class="impulse-section-divider' + (netRtDev !== 'desktop' ? ' has-override' : '') + '" style="margin-top:12px">Routes</div>';
                    html += '<div style="font-size:10px;color:' + ImpC.muted + ';margin:0 0 5px;line-height:1.4">Each route is a connecting line through cards, in order. Use the dropdown to add cards.' + (netRtDev !== 'desktop' ? ' <strong style="color:' + ImpC.text + '">Editing ' + netRtDev + ' routes</strong>' + (netRtInherited ? ' (inherits desktop until you change them).' : '.') : '') + '</div>';
                    html += '<div class="impulse-net-routes-list" style="display:flex;flex-direction:column;gap:5px">';
                    netRoutes.forEach(function(r) { html += impulseNetRouteRow(r, netCards); });
                    html += '</div>';
                    html += '<button type="button" class="instinctor-btn" id="impulse-add-net-route" style="width:100%;margin-top:8px">+ Add route</button>';
                    html += '<input type="hidden" name="' + netRtKey + '" class="impulse-net-routes-input" value="' + escapeHtml(JSON.stringify(netRoutes)) + '">';
                    break;

                case 'marquee':
                    var mqMode = settings.mode || 'icon';
                    html += '<div class="impulse-inline-right"><label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Mode</label>';
                    html += '<div class="impulse-btn-group" data-name="mode" style="display:flex;gap:3px">';
                    [['icon', 'Icon'], ['image', 'Image'], ['testimonial', 'Reviews']].forEach(function (o) { html += '<button type="button" data-value="' + o[0] + '"' + (mqMode === o[0] ? ' class="active"' : '') + ' style="height:26px;padding:0 9px;font-size:11px;box-sizing:border-box">' + o[1] + '</button>'; });
                    html += '<input type="hidden" name="mode" value="' + mqMode + '">';
                    html += '</div></div>';
                    var mqImgStyle = settings.image_style || 'photo';
                    html += '<div class="impulse-inline-right mq-image-style-row" style="margin-top:6px' + (mqMode === 'image' ? '' : ';display:none') + '"><label style="font-size:11px">Image style</label>';
                    html += '<div class="impulse-btn-group" data-name="image_style" style="display:flex;gap:3px">';
                    [['photo', 'Photo'], ['logo', 'Logo']].forEach(function (o) { html += '<button type="button" data-value="' + o[0] + '"' + (mqImgStyle === o[0] ? ' class="active"' : '') + ' style="width:52px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o[1] + '</button>'; });
                    html += '<input type="hidden" name="image_style" value="' + mqImgStyle + '">';
                    html += '</div></div>';
                    var mqCapPos = settings.caption_pos || 'below';
                    html += '<div class="impulse-inline-right mq-image-style-row" style="margin-top:6px' + (mqMode === 'image' ? '' : ';display:none') + '"><label style="font-size:11px">Caption</label>';
                    html += '<div class="impulse-btn-group" data-name="caption_pos" style="display:flex;gap:3px">';
                    [['below', 'Below'], ['overlay', 'Overlay'], ['hover', 'Hover'], ['none', 'None']].forEach(function (o) { html += '<button type="button" data-value="' + o[0] + '"' + (mqCapPos === o[0] ? ' class="active"' : '') + ' style="height:26px;padding:0 7px;font-size:11px;box-sizing:border-box">' + o[1] + '</button>'; });
                    html += '<input type="hidden" name="caption_pos" value="' + mqCapPos + '">';
                    html += '</div></div>';
                    var mqRows = String(parseInt(settings.row_count, 10) || 2);
                    html += '<div class="impulse-inline-right" style="margin-top:8px"><label style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px">Rows</label>';
                    html += '<div class="impulse-btn-group" data-name="row_count" style="display:flex;gap:3px">';
                    ['1', '2', '3'].forEach(function (v) { html += '<button type="button" data-value="' + v + '"' + (mqRows === v ? ' class="active"' : '') + ' style="width:26px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + v + '</button>'; });
                    html += '<input type="hidden" name="row_count" value="' + mqRows + '">';
                    html += '</div></div>';

                    [0, 1, 2].forEach(function (ri) {
                        var dv = settings['dir_' + ri] || (ri % 2 === 0 ? 'left' : 'right');
                        html += '<div class="impulse-inline-right" style="margin-top:6px"><label style="font-size:11px">Row ' + (ri + 1) + '</label>';
                        html += '<div class="impulse-btn-group" data-name="dir_' + ri + '" style="display:flex;gap:3px">';
                        [['left', 'Left'], ['right', 'Right']].forEach(function (o) { html += '<button type="button" data-value="' + o[0] + '"' + (dv === o[0] ? ' class="active"' : '') + ' style="width:52px;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o[1] + '</button>'; });
                        html += '<input type="hidden" name="dir_' + ri + '" value="' + dv + '">';
                        html += '</div></div>';
                    });

                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    html += settingSliderR('speed', 'Speed', settings, 5, 1, 10, '', true);
                    html += settingSliderR('card_width', 'Width', settings, 200, 120, 360, 'px', true);
                    html += settingSliderR('card_height', 'Height', settings, 0, 0, 240, 'px', true);
                    html += settingSliderR('card_radius', 'Radius', settings, 12, 0, 40, 'px', true);
                    html += '</div>';

                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:10px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:' + ImpC.muted + ';cursor:pointer"><input type="checkbox" name="edge_fade"' + (settings.edge_fade !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Faded edges</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:' + ImpC.muted + ';cursor:pointer">Pause on hover <input type="checkbox" name="pause_hover"' + (settings.pause_hover !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '</div>';

                    html += '<div class="impulse-section-divider" style="margin-top:12px">Card style</div>';
                    html += '<div class="impulse-card-row-double" style="margin-top:4px">';
                    html += settingColorSwatch('card_bg', 'Card', settings.card_bg || '', true, true);
                    html += settingColorSwatch('text_color', 'Text', settings.text_color || '', true, false);
                    html += '</div>';
                    html += '<div class="impulse-card-row-double">';
                    html += settingColorSwatch('icon_color', 'Icon', settings.icon_color || '', true, true);
                    html += settingColorSwatch('border_color', 'Border', settings.border_color || '', true, false);
                    html += '</div>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:' + ImpC.muted + ';cursor:pointer;margin-top:8px" title="On hover the card cross-fades to its Hover detail text"><input type="checkbox" name="hover_reveal"' + (settings.hover_reveal ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Reveal detail on hover</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:' + ImpC.muted + ';cursor:pointer;margin-top:8px" title="Translucent cards with a backdrop blur — reads as glass over photos and cinematic backdrops"><input type="checkbox" name="frosted_glass" value="1"' + ((settings.frosted_glass && settings.frosted_glass !== '0') ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Frosted glass</label>';

                    var mqCards = settings.cards;
                    if (typeof mqCards === 'string') { try { mqCards = JSON.parse(mqCards); } catch (e) { mqCards = null; } }
                    if (!impulseMarqueeCardsMatchMode(mqCards, mqMode)) { mqCards = impulseMarqueeStarterCards(mqMode); }
                    var mqCardsLabel = mqMode === 'testimonial' ? 'Reviews' : (mqMode === 'image' ? 'Images' : 'Cards');
                    html += '<div class="impulse-section-divider" style="margin-top:12px">' + mqCardsLabel + '</div>';
                    html += '<div class="impulse-mq-cards-list" style="display:flex;flex-direction:column;gap:6px">';
                    mqCards.forEach(function (c) { html += impulseMarqueeCardRow(c, mqMode); });
                    html += '</div>';
                    html += '<button type="button" class="instinctor-btn" id="impulse-add-mq-card" style="width:100%;margin-top:8px">+ Add card</button>';
                    html += '<input type="hidden" name="cards" value="' + escapeHtml(JSON.stringify(mqCards)) + '">';
                    break;

                case 'booking':
                    html += '<div class="impulse-inline-right"><label style="font-size:11px">Title</label><input type="text" name="title" value="' + escapeHtml(settings.title || 'Book a Service') + '" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:6px"><label style="font-size:11px">Button Text</label><input type="text" name="button_text" value="' + escapeHtml(settings.button_text || 'Book Now') + '" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    
                    html += '<div class="impulse-section-divider" style="margin-top:8px">Colors</div>';
                    html += '<div class="impulse-card-row-double" style="margin-top:4px">';
                    html += settingColorSwatch('button_bg', 'Button', settings.button_bg || ''+ImpC.surface2+'', true, true);
                    html += settingColorSwatch('button_color', 'Button Text', settings.button_color || '#ffffff', true, false);
                    html += '</div>';
                    html += '<div class="impulse-card-row-double">';
                    html += settingColorSwatch('field_bg', 'Field', settings.field_bg || '#ffffff', true, true);
                    html += settingColorSwatch('field_border', 'Field Border', settings.field_border || ''+ImpC.text+'', true, false);
                    html += '</div>';
                    html += '<div class="impulse-card-row-double">';
                    html += settingColorSwatch('card_bg', 'Card', settings.card_bg || '', true, true);
                    html += '</div>';
                    
                    html += '<div class="impulse-section-divider" style="margin-top:8px">Dimensions</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:4px">';
                    html += settingSliderR('max_width', 'Max Width', settings, 560, 300, 900, 'px', true);
                    html += settingSliderR('title_size', 'Title Size', settings, 22, 14, 40, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('field_radius', 'Field Radius', settings, 8, 0, 20, 'px', true);
                    html += settingSliderR('button_radius', 'Button Radius', settings, 8, 0, 20, 'px', true);
                    html += '</div>';
                    html += settingEntranceAnimation(settings);
                    break;

                case 'login':
                    
                    html += '<div class="impulse-inline-right"><label style="font-size:11px">Button Text</label><input type="text" name="button_text" value="' + escapeHtml(settings.button_text || 'Log In') + '" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:8px"><label style="font-size:11px">Redirect URL</label><input type="text" name="redirect_url" value="' + escapeHtml(settings.redirect_url || '') + '" placeholder="Optional" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';

                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:12px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_remember"' + (settings.show_remember !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Remember me</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer">Lost password <input type="checkbox" name="show_lost_password"' + (settings.show_lost_password !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '</div>';
                    html += '<div style="margin-top:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_google"' + (settings.show_google !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Show Google Sign-In</label>';
                    html += '</div>';

                    
                    var _lblAbsLogin = 'position:absolute;bottom:100%;margin-bottom:4px;white-space:nowrap;font-size:11px;color:#aaa';
                    html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-top:24px">';
                    html += '<div style="position:relative"><span style="' + _lblAbsLogin + ';left:0">Button</span>' + settingColorSwatchOnly('button_bg', settings.button_bg || ''+ImpC.surface+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsLogin + ';left:50%;transform:translateX(-50%)">Fields</span>' + settingColorSwatchOnly('field_bg', settings.field_bg || ''+ImpC.light+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsLogin + ';left:50%;transform:translateX(-50%)">Border</span>' + settingColorSwatchOnly('field_border_color', settings.field_border_color || ''+ImpC.text+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsLogin + ';left:50%;transform:translateX(-50%)">Text</span>' + settingColorSwatchOnly('field_text_color', settings.field_text_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsLogin + ';right:0">Label</span>' + settingColorSwatchOnly('field_label_color', settings.field_label_color || '') + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('field_radius', 'Radius', settings, 4, 0, 20, 'px', true);
                    html += settingSliderR('section_max_width', 'Max Width', settings, 400, 200, 800, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('field_gap', 'Field Gap', settings, 16, 3, 20, 'px', true);
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    break;

                case 'register':
                    
                    html += '<div class="impulse-inline-right"><label style="font-size:11px">Button Text</label><input type="text" name="button_text" value="' + escapeHtml(settings.button_text || 'Create Account') + '" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:8px"><label style="font-size:11px">Redirect URL</label><input type="text" name="redirect_url" value="' + escapeHtml(settings.redirect_url || '') + '" placeholder="Optional" style="width:140px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';

                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:12px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_name_fields"' + (settings.show_name_fields !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Name fields</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer">Require name <input type="checkbox" name="require_name"' + (settings.require_name ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '</div>';
                    html += '<div style="margin-top:6px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_google"' + (settings.show_google !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Show Google Sign-In</label>';
                    html += '</div>';

                    
                    var _lblAbsReg = 'position:absolute;bottom:100%;margin-bottom:4px;white-space:nowrap;font-size:11px;color:#aaa';
                    html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-top:24px">';
                    html += '<div style="position:relative"><span style="' + _lblAbsReg + ';left:0">Button</span>' + settingColorSwatchOnly('button_bg', settings.button_bg || ''+ImpC.surface+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsReg + ';left:50%;transform:translateX(-50%)">Fields</span>' + settingColorSwatchOnly('field_bg', settings.field_bg || ''+ImpC.light+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsReg + ';left:50%;transform:translateX(-50%)">Border</span>' + settingColorSwatchOnly('field_border_color', settings.field_border_color || ''+ImpC.text+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsReg + ';left:50%;transform:translateX(-50%)">Text</span>' + settingColorSwatchOnly('field_text_color', settings.field_text_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="position:relative"><span style="' + _lblAbsReg + ';right:0">Label</span>' + settingColorSwatchOnly('field_label_color', settings.field_label_color || '') + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('field_radius', 'Radius', settings, 4, 0, 20, 'px', true);
                    html += settingSliderR('section_max_width', 'Max Width', settings, 400, 200, 800, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('field_gap', 'Field Gap', settings, 16, 3, 20, 'px', true);
                    html += '</div>';

                    html += settingEntranceAnimation(settings);
                    break;

                case 'account':
                    
                    var previewLoggedOut = !!(settings.preview_loggedout);
                    html += '<button type="button" class="impulse-account-preview-toggle" style="display:block;width:100%;height:26px;font-size:11px;margin-bottom:10px;background:' + (previewLoggedOut ? ''+ImpC.white+'' : ''+ImpC.panel+'') + ';color:' + (previewLoggedOut ? ''+ImpC.surface2+'' : ''+ImpC.muted+'') + ';border:1px solid ' + (previewLoggedOut ? '#888' : ''+ImpC.border+'') + ';border-radius:3px;cursor:pointer">' + (previewLoggedOut ? 'Viewing: Logged Out' : 'View as Logged Out') + '</button>';
                    html += '<input type="hidden" name="preview_loggedout" value="' + (previewLoggedOut ? '1' : '') + '">';
                    
                    html += '<div class="impulse-inline-right"><label style="font-size:11px">Title</label>'
                        + '<input type="text" name="title" value="' + escapeHtml(settings.title || 'My Account') + '" placeholder="My Account" style="width:155px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">'
                        + '</div>';
                    
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-top:10px;align-items:end">';
                    html += '<div>' + settingColorSwatch('text_color', 'Text', settings.text_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="text-align:center"><div style="display:flex;justify-content:center">' + settingColorSwatch('nav_active_color', 'Nav Active', settings.nav_active_color || '#ffffff') + '</div></div>';
                    html += '<div style="text-align:right"><div style="display:flex;justify-content:flex-end">' + settingColorSwatch('btn_bg', 'Button', settings.btn_bg || ''+ImpC.surface2+'') + '</div></div>';
                    html += '</div>';
                    
                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    html += settingSliderR('border_radius', 'Radius', settings, 6, 0, 24, 'px', true);
                    html += '<div></div>';
                    html += '</div>';
                    html += settingEntranceAnimation(settings);
                    break;

                case 'receipt':
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">';
                    html += '<div>' + settingColorSwatch('text_color', 'Text', settings.text_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="text-align:right">' + settingColorSwatch('icon_color', 'Accent', settings.icon_color || '#999999') + '</div>';
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('section_max_width', 'Width', settings, 300, 200, 600, 'px', true);
                    html += settingSliderR('border_radius', 'Radius', settings, 8, 0, 24, 'px', true);
                    html += '</div>';
                    html += settingEntranceAnimation(settings);
                    break;
                
                case 'shipping':
                    html += '<div class="impulse-inline-right"><label style="font-size:11px">Text Before</label><input type="text" name="text_before" value="' + escapeHtml(settings.text_before || 'Add {amount} more for free shipping!') + '" style="width:180px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div style="font-size:10px;color:#666;margin:2px 0 6px">{amount} = remaining dollar amount to qualify</div>';
                    html += '<div class="impulse-inline-right"><label style="font-size:11px">Text After</label><input type="text" name="text_after" value="' + escapeHtml(settings.text_after || "You\'ve unlocked free shipping!") + '" style="width:180px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div class="impulse-inline-right" style="margin-top:8px"><label style="font-size:11px">Threshold $</label><input type="text" name="threshold" value="' + escapeHtml(String(settings.threshold || '')) + '" placeholder="Auto" style="width:80px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
                    html += '<div style="font-size:10px;color:#666;margin:2px 0 8px">Required — enter your free shipping minimum order amount</div>';
                    html += '<div style="display:flex;gap:16px;align-items:flex-start;margin-top:8px">';
                    html += '<div style="flex:1;display:flex;flex-direction:column;align-items:flex-start;gap:4px"><label style="font-size:11px;color:'+ImpC.muted+'">Bar Color</label>' + settingColorSwatchOnly('bar_color', settings.bar_color || '#555555') + '</div>';
                    html += '<div style="flex:1;display:flex;flex-direction:column;align-items:flex-end;gap:4px"><label style="font-size:11px;color:'+ImpC.muted+'">Text Color</label>' + settingColorSwatchOnly('text_color', settings.text_color || '#ffffff') + '</div>';
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:12px">';
                    html += settingSliderR('font_size', 'Font Size', settings, 14, 10, 24, 'px', true);
                    html += settingSliderR('bar_height', 'Bar Height', settings, 8, 4, 24, 'px', true);
                    html += '</div>';
                    html += settingEntranceAnimation(settings);
                    break;
                
                case 'header':
                    
                    html += '<div style="margin-bottom:5px">';
                    html += '<button type="button" class="instinctor-btn impulse-save-header-to-library" style="width:100%;height:26px;padding:0 8px;font-size:11px">Save to Library</button>';
                    html += '</div>';

                    html += '<div class="impulse-btn-group" data-name="layout" style="display:flex;width:100%;margin-bottom:5px">';
                    [{v:'logo-left',l:'Left'},{v:'logo-center',l:'Center'},{v:'logo-right',l:'Right'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + ((settings.layout || 'logo-left') === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="layout" value="' + (settings.layout || 'logo-left') + '">';
                    html += '</div>';

                    var dv = window.impulseDevice || 'desktop';
                    function hdrChk(name, defVal) {
                        if (dv !== 'desktop') {
                            var dk = name + '_' + dv;
                            if (settings[dk] !== undefined) return !!settings[dk];
                        }
                        return settings[name] !== undefined ? (defVal ? settings[name] !== false : !!settings[name]) : defVal;
                    }
                    var stickyMode = settings.sticky_mode || (settings.sticky ? 'sticky' : 'off');
                    html += '<div class="impulse-btn-group" data-name="sticky_mode" style="display:flex;width:100%;margin-bottom:5px">';
                    [{v:'off',l:'Static'},{v:'sticky',l:'Sticky'},{v:'auto-hide',l:'Auto-hide'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (stickyMode === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="sticky_mode" value="' + stickyMode + '">';
                    html += '</div>';

                    
                    
                    var hdrBg = settings.header_bg || 'frosted';
                    html += '<div class="impulse-btn-group" data-name="header_bg" style="display:flex;width:100%;margin-bottom:5px">';
                    [{v:'frosted',l:'Frosted'},{v:'solid',l:'Solid'},{v:'transparent',l:'Transparent'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + (hdrBg === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="header_bg" value="' + hdrBg + '">';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:5px 12px;margin-bottom:5px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer" data-responsive="true"><input type="checkbox" name="show_site_name"' + (hdrChk('show_site_name', true) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Site Name</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;justify-content:flex-end" data-responsive="true">Top Bar <input type="checkbox" name="announcement_enabled"' + (hdrChk('announcement_enabled', false) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer" data-responsive="true" title="Bottom border line"><input type="checkbox" name="show_border"' + (hdrChk('show_border', true) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Border</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;justify-content:flex-end" data-responsive="true" title="Subtle shadow under header">Shadow <input type="checkbox" name="show_shadow"' + (hdrChk('show_shadow', false) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer" data-responsive="true" title="Empty cart is hidden"><input type="checkbox" name="show_cart"' + (hdrChk('show_cart', true) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Cart</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;justify-content:flex-end" data-responsive="true">Account <input type="checkbox" name="show_account"' + (hdrChk('show_account', false) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer" data-responsive="true" title="CTA button in header"><input type="checkbox" name="show_cta"' + (hdrChk('show_cta', false) ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> CTA Button</label>';
                    html += '<div></div>';
                    html += '</div>';

                    html += '<div class="impulse-cart-url-option" style="margin-bottom:5px;' + (hdrChk('show_cart', true) ? '' : 'display:none') + '">';
                    html += '<input type="text" name="cart_url" value="' + escapeHtml(settings.cart_url || '/cart') + '" placeholder="Cart page URL" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">';
                    html += '</div>';

                    html += '<div class="impulse-account-url-option" style="margin-bottom:5px;' + (hdrChk('show_account', false) ? '' : 'display:none') + '">';
                    html += '<input type="text" name="account_url" value="' + escapeHtml(settings.account_url || '/account') + '" placeholder="Account page URL" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">';
                    html += '</div>';

                    html += '<div class="impulse-cta-options" style="' + (settings.show_cta ? '' : 'display:none') + '">';
                    html += '<input type="text" name="cta_text" value="' + escapeHtml(settings.cta_text || 'Get Started') + '" placeholder="Button text" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;margin-bottom:5px">';
                    html += '<input type="text" name="cta_url" value="' + escapeHtml(settings.cta_url || '#') + '" placeholder="Button URL" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;margin-bottom:5px">';
                    html += '</div>';

                    html += '<div class="impulse-announcement-options" style="' + (settings.announcement_enabled ? '' : 'display:none') + '">';
                    html += '<input type="text" name="announcement_text" value="' + escapeHtml(settings.announcement_text || '') + '" placeholder="Top bar text" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;margin-bottom:5px">';

                    html += '</div>';

                    html += '<div class="impulse-site-name-options" style="margin-bottom:5px;' + (settings.show_site_name !== false ? '' : 'display:none') + '">';
                    html += '<input type="text" name="site_name" value="' + escapeHtml(settings.site_name || '') + '" placeholder="Site name (leave empty to use site title)" style="width:100%;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;height:26px;min-height:26px">';
                    html += '</div>';

                    html += '<div style="display:flex;gap:4px;margin-bottom:5px">';
                    html += '<div style="flex:1" class="impulse-image-setting" data-name="logo">';
                    html += '<input type="hidden" name="logo" value="' + (settings.logo || '') + '">';
                    if (settings.logo) {
                        html += '<div style="display:flex;align-items:center;gap:6px">';
                        html += '<img src="' + settings.logo + '" class="impulse-logo-preview impulse-select-image-btn" data-name="logo" style="height:26px;width:auto;border-radius:3px;cursor:pointer;border:1px solid '+ImpC.border+'">';
                        html += '<button type="button" class="impulse-remove-image-btn" data-name="logo" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove logo"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                    } else {
                        html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="logo" style="width:100%;height:26px">Select Logo</button>';
                    }
                    html += '</div>';
                    html += '<button type="button" class="impulse-add-menu-item instinctor-btn" style="flex:1;height:26px">Add Menu Item</button>';
                    html += '</div>';

                    var menuItems = settings.menu_items || [{label:'Home',url:'#'},{label:'Shop',url:'#'},{label:'About',url:'#'},{label:'Contact',url:'#'}];
                    html += '<div class="impulse-header-menu-items" data-name="menu_items">';
                    menuItems.forEach(function(item, idx) {
                        html += '<div class="impulse-header-menu-item" data-index="' + idx + '" style="display:flex;gap:6px;margin-bottom:5px">';
                        html += '<input type="text" name="menu_label_' + idx + '" value="' + escapeHtml(item.label || '') + '" placeholder="Label" style="flex:1;min-width:0;height:26px;padding:0 6px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;background:'+ImpC.panel+';color:'+ImpC.text+';box-sizing:border-box">';
                        html += '<input type="text" name="menu_url_' + idx + '" value="' + escapeHtml(item.url || '') + '" placeholder="URL" style="flex:1;min-width:0;height:26px;padding:0 6px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;background:'+ImpC.panel+';color:'+ImpC.text+';box-sizing:border-box">';
                        html += '<button type="button" class="impulse-remove-menu-item" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                        html += '</div>';
                    });
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px 0;margin-bottom:5px">';
                    html += '<div>' + settingColorSwatch('bg_color', 'Background', settings.bg_color || '#ffffff', false) + '</div>';
                    html += '<div style="text-align:center">' + settingColorSwatch('text_color', 'Text', settings.text_color || ''+ImpC.surface2+'', false) + '</div>';
                    html += '<div style="text-align:right">' + settingColorSwatch('hover_color', 'Hover', settings.hover_color || '#666666', false) + '</div>';
                    html += '<div>' + settingColorSwatch('border_color', 'Border', settings.border_color || ''+ImpC.text+'', false) + '</div>';
                    html += '<div class="impulse-cta-color" style="text-align:center;' + (settings.show_cta ? '' : 'display:none') + '">' + settingColorSwatch('cta_bg', 'CTA BG', settings.cta_bg || ''+ImpC.surface2+'', false) + '</div>';
                    html += '<div class="impulse-cta-color" style="text-align:right;' + (settings.show_cta ? '' : 'display:none') + '">' + settingColorSwatch('cta_color', 'CTA Text', settings.cta_color || '#ffffff', false) + '</div>';
                    html += '<div class="impulse-announcement-color" style="' + (settings.announcement_enabled ? '' : 'display:none') + '">' + settingColorSwatch('announcement_bg', 'Bar BG', settings.announcement_bg || ''+ImpC.surface2+'', false) + '</div>';
                    html += '<div class="impulse-announcement-color" style="' + (settings.announcement_enabled ? '' : 'display:none') + '"></div>';
                    html += '<div class="impulse-announcement-color" style="text-align:right;' + (settings.announcement_enabled ? '' : 'display:none') + '">' + settingColorSwatch('announcement_text_color', 'Bar Text', settings.announcement_text_color || '#ffffff', false) + '</div>';
                    html += '</div>';

                    html += '<div class="impulse-margin-grid" style="margin-top:5px">';
                    html += settingSliderR('padding_top', 'Padding', settings, 16, 0, 100, 'px', true);
                    html += settingSliderR('side_padding', 'Side Padding', settings, 40, 0, 100, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:5px">';
                    html += settingSliderR('menu_gap', 'Menu Gap', settings, 32, 16, 48, 'px', true);
                    html += settingSliderR('menu_font_size', 'Font Size', settings, 15, 12, 20, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid" style="margin-top:5px">';
                    html += settingSliderR('icon_size', 'Icon Size', settings, 20, 16, 28, 'px', true);
                    html += settingSliderR('border_width', 'Border Width', settings, 1, 0, 5, 'px', true);
                    html += '</div>';
                    break;
                
                case 'footer':
                    
                    html += '<div style="margin-bottom:6px">';
                    html += '<button type="button" class="instinctor-btn impulse-save-footer-to-library" style="width:100%;height:26px;padding:0 8px;font-size:11px">Save to Library</button>';
                    html += '</div>';

                    html += '<div class="impulse-btn-group" data-name="layout" style="display:flex;width:100%;margin-bottom:8px">';
                    [{v:'4-col',l:'4 Col'},{v:'3-col',l:'3 Col'},{v:'centered',l:'Centered'},{v:'minimal',l:'Minimal'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '"' + ((settings.layout || '4-col') === o.v ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px">' + o.l + '</button>';
                    });
                    html += '<input type="hidden" name="layout" value="' + (settings.layout || '4-col') + '">';
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 12px;margin-bottom:12px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_logo"' + (settings.show_logo ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Show Logo</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;justify-content:flex-end">Social Icons <input type="checkbox" name="show_social"' + (settings.show_social !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_copyright"' + (settings.show_copyright !== false ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Copyright</label>';
                    html += '<div></div>';
                    html += '</div>';

                    html += '<div class="impulse-setting-divider"><span>Link Columns</span></div>';
                    var cols = [
                        {key: 'col1', title: settings.col1_title || 'Company', links: settings.col1_links || [{label:'About',url:'#'},{label:'Careers',url:'#'}]},
                        {key: 'col2', title: settings.col2_title || 'Support', links: settings.col2_links || [{label:'Help',url:'#'},{label:'Contact',url:'#'}]},
                        {key: 'col3', title: settings.col3_title || 'Legal', links: settings.col3_links || [{label:'Privacy',url:'#'},{label:'Terms',url:'#'}]}
                    ];
                    cols.forEach(function(col, colIdx) {
                        html += '<div class="impulse-footer-col-section collapsed" data-col="' + col.key + '" style="margin-bottom:8px">';
                        html += '<div class="impulse-footer-col-trigger" style="display:flex;align-items:center;gap:6px;cursor:pointer">';
                        html += '<svg class="impulse-footer-col-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="#666" stroke-width="2" style="flex-shrink:0;transition:transform 0.15s"><path d="M6 9l6 6 6-6"/></svg>';
                        html += '<input type="text" name="' + col.key + '_title" value="' + escapeHtml(col.title) + '" placeholder="Column Title" class="impulse-footer-col-title" style="flex:1;height:26px;padding:0 8px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;box-sizing:border-box;background:'+ImpC.panel+';color:'+ImpC.text+'">';
                        html += '</div>';
                        html += '<div class="impulse-footer-col-content" style="display:none;padding-top:8px">';
                        html += '<div class="impulse-footer-column-links" data-col="' + col.key + '">';
                        col.links.forEach(function(link, idx) {
                            var hasUrl = !!(link.url && link.url !== '#');
                            html += '<div class="impulse-footer-link-item' + (hasUrl ? ' impulse-url-mode' : '') + '" data-index="' + idx + '" data-url="' + (link.url || '').replace(/"/g, '&quot;') + '" style="display:flex;gap:5px;margin-bottom:6px;align-items:center">';
                            html += '<input type="text" class="impulse-footer-link-text" value="' + escapeHtml(hasUrl ? (link.url || '') : (link.label || '')) + '" placeholder="' + (hasUrl ? 'https://' : 'Link label') + '" style="flex:1;min-width:0;height:26px;padding:0 8px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;box-sizing:border-box;background:'+ImpC.panel+';color:'+ImpC.text+'">';
                            html += '<button type="button" class="impulse-footer-link-url-btn" style="width:26px;height:26px;flex-shrink:0;background:' + (hasUrl ? ''+ImpC.border+'' : ''+ImpC.panel+'') + ';border:1px solid ' + (hasUrl ? ''+ImpC.dim+'' : ''+ImpC.border+'') + ';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Toggle URL"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="' + (hasUrl ? ''+ImpC.white+'' : ''+ImpC.muted+'') + '" stroke-width="2.5"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></button>';
                            html += '<button type="button" class="impulse-remove-footer-link" data-col="' + col.key + '" style="width:26px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                            html += '</div>';
                        });
                        html += '</div>';
                        html += '<button type="button" class="impulse-add-footer-link instinctor-btn" data-col="' + col.key + '" style="width:100%;height:26px;font-size:11px">Add Link</button>';
                        html += '</div>';
                        html += '</div>';
                    });

                    
                    
                    html += '<div class="impulse-setting-divider"><span>Colors</span></div>';
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:6px">';
                    html += '<div style="text-align:left"><div style="font-size:11px;color:#aaa;margin-bottom:4px">BG</div>' + settingColorSwatchOnly('bg_color', settings.bg_color || ''+ImpC.surface2+'') + '</div>';
                    html += '<div style="text-align:center"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Titles</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('heading_color', settings.heading_color || '#ffffff') + '</div></div>';
                    html += '<div style="text-align:center"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Links</div><div style="display:flex;justify-content:center">' + settingColorSwatchOnly('text_color', settings.text_color || '#999999') + '</div></div>';
                    html += '<div style="text-align:right"><div style="font-size:11px;color:#aaa;margin-bottom:4px">Line</div><div style="display:flex;justify-content:flex-end">' + settingColorSwatchOnly('line_color', settings.line_color || '') + '</div></div>';
                    html += '</div>';

                    

                    
                    html += '<div class="impulse-setting-divider"><span>Typography</span></div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('footer_title_size', 'Title size', settings, 14, 10, 28, 'px', true);
                    html += settingSliderR('footer_link_size', 'Link size', settings, 14, 10, 22, 'px', true);
                    html += settingSliderR('footer_line_height', 'Line height', settings, 130, 100, 220, '%', true);
                    html += settingSliderR('padding_top', 'Padding', settings, 60, 0, 200, 'px', true);
                    html += '</div>';
                    break;

                case 'posts':

                    
                    html += '<div class="impulse-inline-right" style="margin-bottom:8px">';
                    html += '<label style="font-size:11px">Heading</label>';
                    html += '<input type="text" name="heading" value="' + escapeHtml(settings.heading || '') + '" placeholder="Optional" style="flex:1;min-width:0;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                    html += '</div>';

                    var _poCols = parseInt(settings.columns) || 2;
                    if (_poCols < 1) _poCols = 1; if (_poCols > 3) _poCols = 3;
                    html += '<div class="impulse-inline-right" style="margin-bottom:8px">';
                    html += '<label style="font-size:11px">Columns</label>';
                    html += '<div class="impulse-btn-group" data-name="columns" style="display:flex;gap:3px">';
                    for (var _pc = 1; _pc <= 3; _pc++) {
                        html += '<button type="button" data-value="' + _pc + '" class="' + (_poCols === _pc ? 'active' : '') + '" style="height:26px;font-size:11px;padding:0 12px">' + _pc + '</button>';
                    }
                    html += '<input type="hidden" name="columns" value="' + _poCols + '">';
                    html += '</div></div>';

                    html += '<div class="impulse-margin-grid" style="margin-bottom:6px">';
                    html += settingSliderR('limit', 'Max Posts', settings, 12, 1, 24, '', true);
                    html += '</div>';

                    html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 12px;margin-top:8px">';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer"><input type="checkbox" name="show_date"' + (settings.show_date !== false && settings.show_date !== '0' ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"> Date</label>';
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;justify-content:flex-end">Excerpt <input type="checkbox" name="show_excerpt"' + (settings.show_excerpt !== false && settings.show_excerpt !== '0' ? ' checked' : '') + ' style="margin:0;width:14px;height:14px"></label>';
                    html += '</div>';
                    break;

            }

            html += '</div>'; 
            
            return html;
        }
        
        function settingText(name, label, value, placeholder, displayValue) {
            var placeholderAttr = placeholder ? ' placeholder="' + escapeHtml(placeholder) + '"' : '';
            displayValue = displayValue !== undefined ? displayValue : (value || '');
            return '<div class="impulse-setting-row"><label>' + label + '</label><input type="text" name="' + name + '" value="' + escapeHtml(displayValue) + '"' + placeholderAttr + '></div>';
        }
        
        function settingTextarea(name, label, value) {
            return '<div class="impulse-setting-row"><label>' + label + '</label><textarea name="' + name + '" rows="4">' + escapeHtml(value) + '</textarea></div>';
        }
        
        function settingRichText(name, label, value, options) {
            options = options || {};
            var rows = options.rows || 4;
            var minHeight = rows * 28; 
            var placeholder = options.placeholder || '';
            var sizeSlider = options.sizeSlider || null; 

            var displayValue = value;
            if (value === 'Add your text content here.' || value === 'Add your text codddddntent here.') {
                displayValue = '';
                placeholder = 'Add your text here...';
            }
            
            var wrapperClass = 'impulse-richtext-wrapper' + (sizeSlider ? ' has-size-slider' : '');
            var html = '<div class="impulse-setting-row impulse-richtext-setting impulse-richtext-nolabel" data-name="' + name + '">';
            html += '<div class="' + wrapperClass + '">';

            html += '<div class="impulse-richtext-toolbar">';
            html += '<div class="impulse-richtext-tabs">';
            html += '<button type="button" class="impulse-richtext-tab active" data-mode="visual">Visual</button>';
            html += '<button type="button" class="impulse-richtext-tab" data-mode="html">HTML</button>';
            html += '</div>';
            html += '<div class="impulse-richtext-buttons">';
            html += '<button type="button" data-cmd="italic" title="Italic"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/></svg></button>';
            html += '<button type="button" data-cmd="underline" title="Underline"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 4v6a6 6 0 0 0 12 0V4"/><line x1="4" x2="20" y1="20" y2="20"/></svg></button>';
            html += '<button type="button" data-cmd="strikeThrough" title="Strikethrough"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4H9a3 3 0 0 0-2.83 4"/><path d="M14 12a4 4 0 0 1 0 8H6"/><line x1="4" x2="20" y1="12" y2="12"/></svg></button>';
            html += '<button type="button" data-cmd="insertUnorderedList" title="Bulleted list"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg></button>';
            html += '</div>';
            html += '</div>';

            html += '<div class="impulse-richtext-editor" contenteditable="true" data-name="' + name + '" data-placeholder="' + placeholder + '" style="min-height:' + minHeight + 'px;font-size:11px">' + (displayValue || '') + '</div>';

            html += '<textarea class="impulse-richtext-html" data-name="' + name + '" style="display:none;min-height:' + minHeight + 'px">' + escapeHtml(displayValue || '') + '</textarea>';

            if (sizeSlider) {
                var sizeVal = sizeSlider.value || sizeSlider.min;
                var responsiveAttr = sizeSlider.responsive ? ' data-responsive="true"' : '';
                html += '<div class="impulse-richtext-size-slider"' + responsiveAttr + ' data-name="' + sizeSlider.name + '">';
                html += '<div class="impulse-richtext-size-popup">' + sizeVal + 'px</div>';
                html += '<input type="range" name="' + sizeSlider.name + '" value="' + sizeVal + '" min="' + sizeSlider.min + '" max="' + sizeSlider.max + '">';
                html += '</div>';
            }

            

            
            var _rtWtMatch = String(displayValue || '').match(/font-weight:\s*(\d+)/);
            var _rtCurWt = _rtWtMatch ? _rtWtMatch[1] : '';
            html += '<label style="font-size:11px;color:#888;margin:8px 0 4px;display:block">Font weight</label>';
            html += '<div class="impulse-weight-popover impulse-weight-inline">';
            html += '<button type="button" data-weight="300" class="' + (_rtCurWt === '300' ? 'active' : '') + '">Light</button>';
            html += '<button type="button" data-weight="400" class="' + (_rtCurWt === '400' ? 'active' : '') + '">Normal</button>';
            html += '<button type="button" data-weight="600" class="' + (_rtCurWt === '600' ? 'active' : '') + '">Semi</button>';
            html += '<button type="button" data-weight="700" class="' + (_rtCurWt === '700' ? 'active' : '') + '">Bold</button>';
            html += '</div>';

            html += '<input type="hidden" name="' + name + '" value="' + escapeHtml(displayValue || '') + '">';
            html += '</div></div>';
            return html;
        }
        
        function settingNumber(name, label, value, min, max) {
            return '<div class="impulse-setting-row"><label>' + label + '</label><input type="number" name="' + name + '" value="' + value + '" min="' + min + '" max="' + max + '"></div>';
        }
        
        function settingSelect(name, label, value, options) {
            var html = '<div class="impulse-setting-row"><label>' + label + '</label><select name="' + name + '">';
            options.forEach(function(o) {
                html += '<option value="' + o.v + '"' + (value === o.v ? ' selected' : '') + '>' + o.l + '</option>';
            });
            return html + '</select></div>';
        }

        

        
        
        var _impulseFontList = [
            {v:'', l:'System Default'},
            {v:'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif', l:'System'},
            {v:'"Helvetica Neue", Helvetica, Arial, sans-serif', l:'Sans'},
            {v:'Georgia, "Times New Roman", "Liberation Serif", serif', l:'Serif'},
            {v:'"Palatino", "Palatino Linotype", "Book Antiqua", "URW Palladio L", serif', l:'Editorial'},
            {v:'"Optima", "Candara", "Trebuchet MS", "Lucida Sans Unicode", sans-serif', l:'Humanist'},
            {v:'"Didot", "Bodoni 72", "Bodoni MT", "Playbill", serif', l:'Couture'},
            {v:'Impact, Haettenschweiler, "Arial Narrow Bold", sans-serif', l:'Display'},
            {v:'"Copperplate", "Copperplate Gothic Light", "Copperplate Gothic Bold", "URW Antiqua", serif', l:'Stamped'},
            {v:'"Snell Roundhand", "Apple Chancery", "Edwardian Script ITC", "Monotype Corsiva", cursive', l:'Script'},
            {v:'"Bradley Hand", "Segoe Script", "Lucida Handwriting", "Comic Sans MS", cursive', l:'Hand'},
            {v:'"Marker Felt", "Chalkboard SE", "Permanent Marker", "Comic Sans MS", fantasy', l:'Marker'},
            {v:'"Chalkduster", "Brush Script MT", "Segoe Print", "Comic Sans MS", fantasy', l:'Chalk'},
            {v:'"SF Mono", Menlo, Consolas, "Liberation Mono", "Courier New", monospace', l:'Mono'},
            {v:'"Courier", "Courier New", "Lucida Sans Typewriter", monospace', l:'Typewriter'}
        ];

        

        

        var _weightRenderCache = {};
        function _fontHasWeight(fontName, weight) {
            weight = String(weight);
            if (!fontName || weight === '400' || weight === 'reset') return true;
            var key = fontName + '|' + weight;
            if (_weightRenderCache[key] !== undefined) return _weightRenderCache[key];
            function widthAt(wt) {
                var s = document.createElement('span');
                s.textContent = 'Weighting Mgpq 018';
                s.style.cssText = 'position:absolute;visibility:hidden;left:-9999px;top:0;white-space:nowrap;font-size:64px;font-weight:' + wt + ';font-family:' + fontName;
                document.body.appendChild(s);
                var w = s.getBoundingClientRect().width;
                s.parentNode.removeChild(s);
                return w;
            }
            var distinct = Math.abs(widthAt(weight) - widthAt('400')) > 0.5;
            _weightRenderCache[key] = distinct;
            return distinct;
        }

        function settingFontPicker(name, value) {
            var curLabel = 'System Default';
            _impulseFontList.forEach(function(f) { if (f.v === value) curLabel = f.l; });
            var html = '<div class="impulse-font-picker" style="margin-top:8px;position:relative">';
            html += '<label style="font-size:11px;color:#888;margin-bottom:4px;display:block">Font</label>';
            html += '<div class="impulse-font-trigger" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:12px;padding:0 8px;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;justify-content:space-between;' + (value ? 'font-family:' + value : '') + '">';
            html += '<span class="impulse-font-trigger-label">' + curLabel + '</span>';
            html += '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="'+ImpC.muted+'" stroke-width="2"><path d="m6 9 6 6 6-6"/></svg>';
            html += '</div>';
            html += '<div class="impulse-font-options" style="display:none">';
            _impulseFontList.forEach(function(f) {
                html += '<div class="impulse-font-option' + (f.v === value ? ' active' : '') + '" data-value="' + f.v.replace(/"/g, '&quot;') + '" style="' + (f.v ? 'font-family:' + f.v : '') + '">' + f.l + '</div>';
            });
            html += '</div>';
            html += '<input type="hidden" name="' + name + '" value="' + (value || '') + '">';
            html += '</div>';
            return html;
        }
        
        function settingCheckbox(name, label, checked) {
            return '<div class="impulse-setting-row" style="display:flex;align-items:center;justify-content:space-between"><label style="margin:0">' + label + '</label><input type="checkbox" name="' + name + '" value="1"' + (checked ? ' checked' : '') + '></div>';
        }
        
        function buildBgEffectSettingsSimple(effect, s, layerOpacity, layerZIndex) {
            var html = '';
            s = s || {};
            if (!effect) return '';
            var opacity = layerOpacity !== undefined ? layerOpacity : 100;
            var zIdx = layerZIndex !== undefined ? layerZIndex : 0;

            

            

            

            
            if (effect === 'lava') {
                html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">';
                [['color','#16181c'],['color_2','#2d3580'],['color_3','#5040b0'],['color_4','#7038ff']].forEach(function(c){
                    html += '<div class="impulse-section-anim-color-wrap" data-key="' + c[0] + '">' + settingColorSwatchOnly('section_anim_lava_' + c[0], s[c[0]] || c[1]) + '</div>';
                });
                html += '</div>';
                html += '<div class="impulse-margin-grid">';

                
                
                var lavaSpeed = (s.speed !== undefined) ? s.speed : 3;
                html += '<div class="impulse-setting-row inline-slider"><label>Speed</label><span class="impulse-slider-value">' + lavaSpeed + '</span><div class="impulse-slider-row" data-unit=""><input type="range" class="impulse-bg-setting" data-key="speed" value="' + lavaSpeed + '" min="1" max="10" step="1"></div></div>';

                
                var lavaMS = (s.mouse_sens !== undefined) ? s.mouse_sens : 5;
                html += '<div class="impulse-setting-row inline-slider"><label>Mouse sensitivity</label><span class="impulse-slider-value">' + lavaMS + '</span><div class="impulse-slider-row" data-unit=""><input type="range" class="impulse-bg-setting" data-key="mouse_sens" value="' + lavaMS + '" min="0" max="10" step="1"></div></div>';

                

                
                var lavaDepth = (s.shadow_scale !== undefined) ? s.shadow_scale : 100;
                html += '<div class="impulse-setting-row inline-slider"><label>Depth</label><span class="impulse-slider-value">' + lavaDepth + '</span><div class="impulse-slider-row" data-unit=""><input type="range" class="impulse-bg-setting" data-key="shadow_scale" value="' + lavaDepth + '" min="0" max="100" step="1"></div></div>';

                

                var lavaEdge = (s.edge_sharpness !== undefined) ? s.edge_sharpness : 50;
                html += '<div class="impulse-setting-row inline-slider"><label>Edge</label><span class="impulse-slider-value">' + lavaEdge + '</span><div class="impulse-slider-row" data-unit=""><input type="range" class="impulse-bg-setting" data-key="edge_sharpness" value="' + lavaEdge + '" min="0" max="100" step="1"></div></div>';
                html += '</div>';
                return html;
            }

            function bgBtnGroupCell(key, label, options, defaultVal) {
                var val = s[key] !== undefined ? String(s[key]) : String(defaultVal);
                var h = '<div style="margin-top:8px"><label style="font-size:11px;color:#888;display:block;margin-bottom:4px">' + label + '</label><div class="impulse-btn-group impulse-bg-btn-group" data-key="' + key + '" style="display:flex;width:100%;gap:3px">';
                options.forEach(function(opt) {
                    h += '<button type="button" data-value="' + opt.v + '"' + (String(opt.v) === val ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + opt.l + '</button>';
                });
                h += '</div></div>';
                return h;
            }

            function bgCheckboxCell(key, label, defaultVal) {
                var checked = s[key] !== undefined ? s[key] : defaultVal;
                return '<div class="impulse-setting-row impulse-checkbox-row"><label><input type="checkbox" class="impulse-bg-setting" data-key="' + key + '"' + (checked ? ' checked' : '') + '> ' + label + '</label></div>';
            }

            function bgSliderCell(key, label, value, min, max, unit, step) {
                var val = s[key] !== undefined ? s[key] : value;
                var u = unit || '';
                var stepAttr = step ? ' step="' + step + '"' : '';
                return '<div class="impulse-setting-row inline-slider"><label>' + label + '</label><span class="impulse-slider-value">' + val + u + '</span><div class="impulse-slider-row" data-unit="' + u + '"><input type="range" class="impulse-bg-setting" data-key="' + key + '" value="' + val + '" min="' + min + '" max="' + max + '"' + stepAttr + '></div></div>';
            }

            

            

            function _bgDevKey(key) {
                var d = window.impulseDevice || 'desktop';
                return d === 'desktop' ? key : (key + '_' + d);
            }
            function _bgDevVal(key, fallback) {
                var dk = _bgDevKey(key);
                if (s[dk] !== undefined && s[dk] !== '') return s[dk];
                if (s[key] !== undefined && s[key] !== '') return s[key];
                return fallback;
            }
            function bgSliderCellResp(key, label, value, min, max, unit, step) {
                var dk = _bgDevKey(key);
                var val = _bgDevVal(key, value);
                var u = unit || '';
                var stepAttr = step ? ' step="' + step + '"' : '';
                return '<div class="impulse-setting-row inline-slider"><label>' + label + '</label><span class="impulse-slider-value">' + val + u + '</span><div class="impulse-slider-row" data-unit="' + u + '"><input type="range" class="impulse-bg-setting" data-key="' + dk + '" value="' + val + '" min="' + min + '" max="' + max + '"' + stepAttr + '></div></div>';
            }
            function bgBtnGroupCellResp(key, label, options, defaultVal) {
                var dk = _bgDevKey(key);
                var val = String(_bgDevVal(key, defaultVal));
                var h = '<div style="margin-top:8px"><label style="font-size:11px;color:#888;display:block;margin-bottom:4px">' + label + '</label><div class="impulse-btn-group impulse-bg-btn-group" data-key="' + dk + '" style="display:flex;width:100%;gap:3px">';
                options.forEach(function(opt) {
                    h += '<button type="button" data-value="' + opt.v + '"' + (String(opt.v) === val ? ' class="active"' : '') + ' style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + opt.l + '</button>';
                });
                h += '</div></div>';
                return h;
            }
            function bgCheckboxCellResp(key, label, defaultVal) {
                var dk = _bgDevKey(key);
                var raw = _bgDevVal(key, defaultVal);
                var checked = (raw === true || raw === 'true' || raw === 1 || raw === '1');
                if (raw === false || raw === 'false' || raw === 0 || raw === '0') checked = false;
                return '<div class="impulse-setting-row impulse-checkbox-row"><label><input type="checkbox" class="impulse-bg-setting" data-key="' + dk + '"' + (checked ? ' checked' : '') + '> ' + label + '</label></div>';
            }

            

            

            

            var gradientEffects = ['rings','burst','concentric','hex_grid','ring_trace'];
            var supportsGradient = gradientEffects.indexOf(effect) !== -1;
            var supportsLineColor = (effect === 'network');
            var hasSecondary = supportsGradient || supportsLineColor;
            var lblStyle = 'font-size:11px;color:#888;line-height:1';
            if (hasSecondary) {
                html += '<div style="display:grid;grid-template-columns:1fr 1fr;align-items:end;column-gap:6px;margin-bottom:8px">';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-start;gap:5px">';
                html +=   '<label style="' + lblStyle + '">Main</label>';
                html +=   '<div class="impulse-section-anim-color-wrap" data-key="color">' + settingColorSwatchOnly('section_anim_color_main', s.color || '#888888') + '</div>';
                html += '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end;gap:5px">';
                if (supportsLineColor) {
                    html += '<label style="' + lblStyle + '">Line Color</label>';
                    html += '<div class="impulse-section-anim-color-wrap" data-key="line_color">' + settingColorSwatchOnly('section_anim_net_secondary', (s.line_color || s.color || '#888888')) + '</div>';
                } else {
                    html += '<label style="' + lblStyle + '">Gradient</label>';
                    html += '<div class="impulse-section-anim-color-wrap" data-key="color_2">' + settingColorSwatchOnly('section_anim_color2', s.color_2 || 'rgba(0,0,0,0)') + '</div>';
                }
                html += '</div>';
                html += '</div>';
            } else {
                html += '<div style="display:flex;flex-direction:column;align-items:flex-start;gap:5px;margin-bottom:8px">';
                html +=   '<label style="' + lblStyle + '">Main</label>';
                html +=   '<div class="impulse-section-anim-color-wrap" data-key="color">' + settingColorSwatchOnly('section_anim_color_main', s.color || '#888888') + '</div>';
                html += '</div>';
            }

            var centerEffects = ['rings','burst','spiral','starburst','concentric'];
            if (centerEffects.indexOf(effect) !== -1) {
                html += '<div class="impulse-margin-grid">';
                html += bgSliderCell('origin_x', 'Origin X', 50, 0, 100, '%');
                html += bgSliderCell('origin_y', 'Origin Y', 50, 0, 100, '%');
                html += '</div>';
            }

            var checkboxHtml = '';

            switch (effect) {
                case 'rings':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('thickness', 'Thickness', 3, 1, 100, 'px');
                    html += bgSliderCell('spacing', 'Spacing', 50, 10, 200, 'px');
                    html += bgSliderCell('thickness_decay', 'Thickness Decay', 0, 0, 100, '%');
                    html += bgSliderCell('opacity_decay', 'Opacity Decay', 0, 0, 100, '%');
                    html += bgSliderCell('gradient_mouse', 'Gradient Spin', 0, 0, 100, '%');
                    html += '</div>';
                    break;

                case 'ring_trace':

                    

                    

                    

                    

                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCellResp('speed', 'Speed', 1, 1, 10, '', 1);
                    html += bgSliderCellResp('thickness', 'Thickness', 6, 1, 50, 'px');
                    html += bgSliderCellResp('radius_px', 'Radius', 200, 100, 600, 'px');
                    html += bgSliderCellResp('origin_angle', 'Origin', 180, 0, 359, '°');
                    html += bgSliderCellResp('hold_pct', 'Hold', 100, 0, 300, '%');
                    html += bgSliderCellResp('gradient_spin', 'Grad Spin', 0, 0, 100, '%');

                    

                    

                    html += bgSliderCellResp('delay', 'Delay', 0, 0, 3, 's', 0.1);
                    html += '</div>';

                    

                    html += bgBtnGroupCellResp('stroke_type', 'Stroke', [
                        { v: 'solid',  l: 'Solid' },
                        { v: 'neon',   l: 'Neon' },
                        { v: 'sketch', l: 'Sketch' },
                        { v: 'streak', l: 'Streak' }
                    ], 'solid');

                    

                    
                    
                    function _rtCheckbox(key, label, defaultVal, cbFirst, justify) {
                        var dk = _bgDevKey(key);
                        var raw = _bgDevVal(key, defaultVal);
                        var checked = (raw === true || raw === 'true' || raw === 1 || raw === '1');
                        if (raw === false || raw === 'false' || raw === 0 || raw === '0') checked = false;
                        var cbHtml = '<input type="checkbox" class="impulse-bg-setting" data-key="' + dk + '"' + (checked ? ' checked' : '') + '>';
                        var lbHtml = '<span>' + label + '</span>';
                        var inner = cbFirst ? (cbHtml + lbHtml) : (lbHtml + cbHtml);

                        

                        
                        
                        return '<label style="display:inline-flex;align-items:center;gap:8px;margin:0;cursor:pointer;font-size:11px;color:var(--imp-text);user-select:none;justify-self:' + justify + '">' + inner + '</label>';
                    }
                    checkboxHtml += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:8px">'
                                 +     _rtCheckbox('loop',      'Loop',      true, true,  'start')  
                                 +     _rtCheckbox('show_head', 'Show head', true, false, 'end')    
                                 + '</div>';
                    break;

                case 'burst':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('line_count', 'Lines', 12, 4, 48, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('thickness', 'Thickness', 2, 1, 100, 'px');
                    html += bgSliderCell('dash_length', 'Dash', 20, 5, 100, 'px');
                    html += bgSliderCell('gap', 'Gap', 15, 5, 100, 'px');
                    html += bgSliderCell('line_decay', 'Decay', 0, 0, 100, '%');
                    html += bgSliderCell('gradient_mouse', 'Gradient Spin', 0, 0, 100, '%');
                    html += '</div>';
                    break;

                case 'spiral':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('arm_count', 'Arms', 3, 1, 12, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('thickness', 'Thickness', 3, 1, 100, 'px');
                    html += bgSliderCell('tightness', 'Tightness', 5, 1, 20, '');
                    html += '</div>';
                    break;

                case 'starburst':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('ray_count', 'Rays', 16, 4, 64, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('thickness', 'Thickness', 1, 1, 100, 'px');
                    html += '</div>';
                    break;

                case 'concentric':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('ring_count', 'Rings', 4, 1, 10, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('thickness', 'Thickness', 2, 1, 100, 'px');
                    html += bgSliderCell('radius', 'Radius', 80, 20, 150, '%');
                    html += bgSliderCell('dash_length', 'Dash', 20, 0, 100, 'px');
                    html += bgSliderCell('depth_3d', '3D Depth', 0, 0, 100, '%');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += bgSliderCell('gradient_mouse', 'Gradient Spin', 0, 0, 100, '%');
                    html += '</div>';
                    break;

                case 'squares':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('count', 'Squares', 30, 10, 100, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('life', 'Flight Time', 3, 1, 10, 's', 0.5);
                    html += bgSliderCell('max_size', 'Max Size', 50, 10, 200, 'px');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += bgSliderCell('depth_blur', 'Depth Blur', 0, 0, 10, 'px');
                    html += '</div>';
                    checkboxHtml += bgCheckboxCell('fill', 'Filled', s.fill || false);
                    break;
                    
                case 'orbs':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('count', 'Orbs', 6, 2, 20, '');
                    html += bgSliderCell('speed', 'Speed', 2, 1, 10, '', 1);
                    html += bgSliderCell('max_size', 'Max Size', 200, 50, 500, 'px');
                    html += bgSliderCell('min_size', 'Min Size', 60, 20, 200, 'px');
                    html += bgSliderCell('softness', 'Softness', 50, 0, 100, '%');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += '</div>';
                    break;

                case 'bokeh':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('count', 'Circles', 20, 5, 60, '');
                    html += bgSliderCell('speed', 'Speed', 1, 1, 10, '', 1);
                    html += bgSliderCell('max_size', 'Max Size', 80, 20, 200, 'px');
                    html += bgSliderCell('min_size', 'Min Size', 10, 5, 60, 'px');
                    html += bgSliderCell('softness', 'Softness', 70, 0, 100, '%');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += '</div>';
                    checkboxHtml += bgCheckboxCell('show_rings', 'Show rings', s.show_rings !== undefined ? s.show_rings : true);
                    break;

                case 'morphing':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('count', 'Blobs', 4, 2, 10, '');
                    html += bgSliderCell('speed', 'Speed', 2, 1, 10, '', 1);
                    html += bgSliderCell('max_size', 'Max Size', 250, 80, 600, 'px');
                    html += bgSliderCell('min_size', 'Min Size', 80, 20, 200, 'px');
                    html += bgSliderCell('complexity', 'Complexity', 5, 3, 12, '');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += '</div>';
                    checkboxHtml += bgCheckboxCell('show_outline', 'Show outline', s.show_outline !== undefined ? s.show_outline : true);
                    break;
                    
                case 'bubbles':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('count', 'Bubbles', 25, 5, 80, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('max_size', 'Max Size', 30, 8, 80, 'px');
                    html += bgSliderCell('min_size', 'Min Size', 4, 2, 20, 'px');
                    html += bgSliderCell('wobble', 'Wobble', 30, 0, 100, 'px');
                    html += bgSliderCell('depth_blur', 'Depth Blur', 0, 0, 10, 'px');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += '</div>';
                    break;
                    
                case 'sine':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('origin_y', 'Vertical Pos', 50, 0, 100, '%');
                    html += bgSliderCell('wave_count', 'Waves', 3, 1, 8, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('amplitude', 'Amplitude', 40, 10, 150, 'px');
                    html += bgSliderCell('frequency', 'Frequency', 2, 0.5, 6, '', 0.1);
                    html += bgSliderCell('thickness', 'Thickness', 2, 1, 100, 'px');
                    html += '</div>';
                    checkboxHtml += bgCheckboxCell('fill', 'Fill below wave', s.fill || false);
                    break;
                    
                case 'aurora':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('band_count', 'Bands', 3, 1, 6, '');
                    html += bgSliderCell('speed', 'Speed', 1, 1, 10, '', 1);
                    html += bgSliderCell('amplitude', 'Amplitude', 60, 10, 200, 'px');
                    html += bgSliderCell('band_width', 'Band Width', 80, 20, 200, 'px');
                    html += bgSliderCell('softness', 'Softness', 60, 0, 100, '%');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += '</div>';
                    break;
                    
                case 'liquid':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('wave_count', 'Waves', 3, 1, 6, '');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('amplitude', 'Height', 60, 10, 200, 'px');
                    html += bgSliderCell('frequency', 'Frequency', 2, 0.5, 6, '', 0.1);
                    html += '</div>';
                    html += bgBtnGroupCell('position', 'Position', [
                        {v:'bottom',l:'Bottom'},{v:'top',l:'Top'}
                    ], s.position || 'bottom');
                    break;
                    
                case 'dot_matrix':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('spacing', 'Spacing', 30, 10, 80, 'px');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('max_size', 'Dot Size', 4, 1, 12, 'px');
                    html += bgSliderCell('wave_radius', 'Wave Radius', 150, 50, 500, 'px');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += '</div>';
                    break;
                    
                case 'hex_grid':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('cell_size', 'Cell Size', 30, 15, 80, 'px');
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('thickness', 'Thickness', 1, 0.5, 100, 'px', 0.5);
                    html += bgSliderCell('glow', 'Fill Opacity', 30, 0, 100, '%');
                    html += bgSliderCell('wave_radius', 'Radius', 200, 50, 600, 'px');
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += bgSliderCell('mouse_reactivity', 'Mouse', 0, 0, 100, '%');
                    html += '</div>';
                    html += bgBtnGroupCell('fill_mode', 'Fill Movement', [
                        {v:'wave',l:'Wave'},{v:'slide',l:'Slide'},{v:'pulse',l:'Pulse'},{v:'radial',l:'Radial'}
                    ], s.fill_mode || 'wave');
                    break;
                    
                case 'network':

                    
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('count', 'Points', 40, 10, 100, '');
                    html += bgSliderCell('speed', 'Speed', 1, 1, 10, '', 1);
                    html += bgSliderCell('link_distance', 'Link Dist', 120, 40, 300, 'px');
                    html += bgSliderCell('max_size', 'Dot Size', 3, 0, 8, 'px');
                    html += bgSliderCell('thickness', 'Line Width', 1, 0.5, 100, 'px', 0.5);
                    html += bgSliderCell('depth_blur', 'Depth Blur', 0, 0, 10, 'px');
                    html += '</div>';
                    break;

                case 'gradient':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('speed', 'Speed', 1, 1, 10, '', 1);
                    html += bgSliderCell('spread', 'Spread', 50, 10, 100, '%');
                    html += bgSliderCell('softness', 'Softness', 50, 0, 100, '%');
                    html += bgSliderCell('size', 'Size', 50, 10, 100, '%');
                    html += '</div>';
                    break;

                case 'caustics':
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('spacing', 'Bands', 50, 16, 200, '');
                    html += bgSliderCell('thickness', 'Thickness', 3, 1, 20, 'px');
                    html += bgSliderCell('softness', 'Softness', 60, 0, 100, '%');
                    html += '</div>';
                    break;

                default:
                    html += '<div class="impulse-margin-grid">';
                    html += bgSliderCell('speed', 'Speed', 3, 1, 10, '', 1);
                    html += bgSliderCell('color_variation', 'Color Shift', 0, 0, 100, '%');
                    html += '</div>';
            }

            

            
            
            if (checkboxHtml) {
                html += '<div style="margin-top:8px">' + checkboxHtml + '</div>';
            }

            return html;
        }

        

        
        function settingWidthPreset(settings) {
            var pct = parseInt(settings.width_pct);
            if (isNaN(pct) || pct < 30) pct = 90;
            if (pct > 100) pct = 100;
            return settingSliderR('width_pct', 'Content width', { width_pct: pct }, 90, 30, 100, '%');
        }

        function settingBtnGroup(name, label, value, options) {
            var html = '<div class="impulse-setting-row"><label>' + label + '</label><div class="impulse-btn-group" data-name="' + name + '">';
            options.forEach(function(o) {
                html += '<button type="button" data-value="' + o.v + '"' + (value === o.v ? ' class="active"' : '') + '>' + o.l + '</button>';
            });
            html += '<input type="hidden" name="' + name + '" value="' + value + '">';
            return html + '</div></div>';
        }

        function settingBtnGroupFull(name, label, value, options) {
            var labelHtml = label ? '<label>' + label + '</label>' : '';
            var html = '<div class="impulse-setting-row"><div class="impulse-btn-group" data-name="' + name + '" style="display:flex;width:100%">';
            options.forEach(function(o) {
                html += '<button type="button" data-value="' + o.v + '"' + (value === o.v ? ' class="active"' : '') + ' style="flex:1">' + o.l + '</button>';
            });
            html += '<input type="hidden" name="' + name + '" value="' + value + '">';
            return labelHtml + html + '</div></div>';
        }

        function settingVisibility(settings) {
            var device = window.impulseDevice || 'desktop';
            var value = getResponsiveValue(settings, 'visibility', 'all', device);
            
            var hasOverride = hasDeviceOverride(settings, 'visibility', device);
            var overrideClass = hasOverride ? ' has-override' : '';
            
            var options = [{v:'off',l:'Off',w:'36px'},{v:'all',l:'All',w:'36px'},{v:'logged_in',l:'Logged In',w:null},{v:'logged_out',l:'Logged Out',w:null}];
            var html = '<div class="impulse-setting-row' + overrideClass + '" data-responsive="true">';
            html += '<div class="impulse-btn-group impulse-btn-group-visibility" data-name="visibility" style="display:flex;width:100%;gap:3px">';
            options.forEach(function(o) {
                var flexStyle = o.w ? 'flex:0 0 ' + o.w + ';width:' + o.w : 'flex:1';
                html += '<button type="button" data-value="' + o.v + '"' + (value === o.v ? ' class="active"' : '') + ' style="' + flexStyle + ';height:26px;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
            });
            html += '<input type="hidden" name="visibility" value="' + value + '">';
            html += '</div></div>';
            return html;
        }
        
        function settingColor(name, label, value, showOpacity) {
            
            var r = 255, g = 255, b = 255, a = 1;
            var hexVal = '#ffffff';
            
            if (value) {
                if (value.startsWith('rgba')) {
                    var match = value.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                    if (match) {
                        r = parseInt(match[1]);
                        g = parseInt(match[2]);
                        b = parseInt(match[3]);
                        a = match[4] ? parseFloat(match[4]) : 1;
                        hexVal = '#' + r.toString(16).padStart(2,'0') + g.toString(16).padStart(2,'0') + b.toString(16).padStart(2,'0');
                    }
                } else if (value.startsWith('#')) {
                    hexVal = value.length === 4 ? 
                        '#' + value[1]+value[1] + value[2]+value[2] + value[3]+value[3] : value;
                    r = parseInt(hexVal.substr(1,2), 16);
                    g = parseInt(hexVal.substr(3,2), 16);
                    b = parseInt(hexVal.substr(5,2), 16);
                } else if (value === 'transparent') {
                    a = 0;
                }
            }

            var hsv = rgbToHsv(r, g, b);
            var hue = Math.round(hsv.h);
            var sat = Math.round(hsv.s);
            var val = Math.round(hsv.v);
            var alphaPercent = Math.round(a * 100);

            var previewColor = a < 1 ? 'rgba('+r+','+g+','+b+','+a+')' : hexVal;
            var hueColor = 'hsl('+hue+',100%,50%)';
            var alphaGradient = 'linear-gradient(to right, transparent, '+hexVal+')';

            

            var trueDefault = value || '#ffffff';

            var html = '<div class="impulse-setting-row impulse-color-setting" data-name="' + name + '">';
            html += '<label>' + label + '</label>';
            html += '<div class="impulse-color-row">';
            html += '<div class="impulse-color-swatch" style="--swatch-color:' + previewColor + '" data-default="' + trueDefault + '"></div>';
            html += '<input type="hidden" name="' + name + '" value="' + (value || '') + '" class="impulse-color-text">';

            html += '<div class="impulse-color-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'" data-alpha="'+alphaPercent+'">';
            html += '<div class="impulse-picker-gradient" style="background-color:'+hueColor+'">';
            html += '<div class="impulse-picker-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div>';
            html += '</div>';
            html += '<div class="impulse-picker-sliders">';
            html += '<div class="impulse-picker-slider-row">';
            html += '';
            html += '<div class="impulse-picker-hue"><div class="impulse-picker-thumb" style="left:'+((hue/360)*100)+'%"></div></div>';
            html += '</div>';
            if (showOpacity !== false) {
                html += '<div class="impulse-picker-slider-row">';
                html += '';
                html += '<div class="impulse-picker-alpha" style="--alpha-gradient:'+alphaGradient+'"><div class="impulse-picker-thumb" style="left:'+alphaPercent+'%"></div></div>';
                html += '</div>';
            }
            html += '</div>';
            html += '<div class="impulse-picker-tools">';
            html += '<div class="impulse-picker-hex"><input type="text" value="' + hexVal + '" placeholder="#000000"></div>';
            html += '<button type="button" class="impulse-picker-eyedropper" title="Pick color from screen"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.71 5.63l-2.34-2.34a1 1 0 00-1.41 0l-3.12 3.12-1.42-1.42-1.41 1.42 1.41 1.41-6.6 6.6a2 2 0 00-.57 1.2l-.67 4.03 4.03-.67a2 2 0 001.2-.57l6.6-6.6 1.41 1.41 1.42-1.41-1.42-1.42 3.13-3.13a1 1 0 000-1.41z"/></svg></button>';
            html += '</div>';
            html += '</div>';
            
            html += '</div>';
            html += '</div>';
            return html;
        }

        function settingColorSwatch(name, label, value, inline, swatchFirst, defaultValue) {
            var r = 255, g = 255, b = 255, a = 1;
            var hexVal = '#ffffff';

            
            var trueDefault = defaultValue || value || '#ffffff';
            
            if (value) {
                if (value.startsWith('rgba')) {
                    var match = value.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                    if (match) {
                        r = parseInt(match[1]);
                        g = parseInt(match[2]);
                        b = parseInt(match[3]);
                        a = match[4] ? parseFloat(match[4]) : 1;
                        hexVal = '#' + r.toString(16).padStart(2,'0') + g.toString(16).padStart(2,'0') + b.toString(16).padStart(2,'0');
                    }
                } else if (value.startsWith('#')) {
                    hexVal = value.length === 4 ? 
                        '#' + value[1]+value[1] + value[2]+value[2] + value[3]+value[3] : value;
                    r = parseInt(hexVal.substr(1,2), 16);
                    g = parseInt(hexVal.substr(3,2), 16);
                    b = parseInt(hexVal.substr(5,2), 16);
                } else if (value === 'transparent') {
                    a = 0;
                }
            }
            
            var hsv = rgbToHsv(r, g, b);
            var hue = Math.round(hsv.h);
            var sat = Math.round(hsv.s);
            var val = Math.round(hsv.v);
            var alphaPercent = Math.round(a * 100);
            
            var previewColor = a < 1 ? 'rgba('+r+','+g+','+b+','+a+')' : hexVal;
            var hueColor = 'hsl('+hue+',100%,50%)';
            var alphaGradient = 'linear-gradient(to right, transparent, '+hexVal+')';
            
            var html = '<div class="impulse-color-setting impulse-color-swatch-only' + (inline ? ' impulse-color-inline' : '') + '" data-name="' + name + '"' + (inline ? ' style="display:flex;align-items:center;gap:6px"' : ' style="display:inline-block"') + '>';
            
            if (!inline) {
                html += '<div class="impulse-color-swatch-label" style="font-size:11px;color:#aaa;margin-bottom:4px">' + label + '</div>';
            } else if (!swatchFirst) {
                html += '<span style="font-size:11px;color:#aaa">' + label + '</span>';
            }
            html += '<div class="impulse-color-row">';
            html += '<div class="impulse-color-swatch" style="--swatch-color:' + previewColor + '"></div>';
            html += '<input type="hidden" name="' + name + '" value="' + (value || '') + '" class="impulse-color-text">';

            html += '<div class="impulse-color-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'" data-alpha="'+alphaPercent+'">';
            html += '<div class="impulse-picker-gradient" style="background-color:'+hueColor+'">';
            html += '<div class="impulse-picker-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div>';
            html += '</div>';
            html += '<div class="impulse-picker-sliders">';
            html += '<div class="impulse-picker-slider-row">';
            html += '<div class="impulse-picker-hue"><div class="impulse-picker-thumb" style="left:'+((hue/360)*100)+'%"></div></div></div>';
            html += '<div class="impulse-picker-slider-row">';
            html += '<div class="impulse-picker-alpha" style="--alpha-gradient:'+alphaGradient+'"><div class="impulse-picker-thumb" style="left:'+alphaPercent+'%"></div></div></div>';
            html += '</div>';
            html += '<div class="impulse-picker-tools">';
            html += '<div class="impulse-picker-hex"><input type="text" value="' + hexVal + '" placeholder="#000000"></div>';
            html += '<button type="button" class="impulse-picker-eyedropper" title="Pick color from screen"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.71 5.63l-2.34-2.34a1 1 0 00-1.41 0l-3.12 3.12-1.42-1.42-1.41 1.42 1.41 1.41-6.6 6.6a2 2 0 00-.57 1.2l-.67 4.03 4.03-.67a2 2 0 001.2-.57l6.6-6.6 1.41 1.41 1.42-1.41-1.42-1.42 3.13-3.13a1 1 0 000-1.41z"/></svg></button>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            if (inline && swatchFirst) {
                html += '<span style="font-size:11px;color:#aaa">' + label + '</span>';
            }
            html += '</div>';
            return html;
        }

        function getFeatureIconPreview(iconType, color) {
            color = color || ''+ImpC.muted+'';
            var icons = {
                'plus-square': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>',
                'check-square': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><polyline points="9 11 12 14 22 4"/></svg>',
                'check-circle': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="9 12 12 15 16 9"/></svg>',
                'check': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',
                'plus-circle': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>',
                'circle-dot': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="' + color + '"/></svg>',
                'x': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',
                'x-square': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9" y2="15"/></svg>',
                'x-circle': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
                'minus-square': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="8" y1="12" x2="16" y2="12"/></svg>',
                'minus-circle': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="8" y1="12" x2="16" y2="12"/></svg>',
                'square': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>',
                'chevron-down': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>',
                'plus': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>',
                'arrow-down': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>',
                'caret-down': '<svg width="14" height="14" viewBox="0 0 24 24" fill="' + color + '" stroke="none"><path d="M6 9l6 6 6-6z"/></svg>',
                'circle-plus': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>',
                'star': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>',
                'heart': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>',
                'arrow-right': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>',
                'chevron-right': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>',
                'zap': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',
                'minus': '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + color + '" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg>'
            };
            return icons[iconType] || icons['plus-square'];
        }

        window.impulseColorSwatchHtml = function(name, value, tooltip) {
            return settingColorSwatchOnly(name, value, tooltip);
        };
        function settingColorSwatchOnly(name, value, tooltip, emptyDisplayColor) {
            var r = 255, g = 255, b = 255, a = 1;
            var hexVal = '#ffffff';

            

            
            
            var _disp = (value !== undefined && value !== null && value !== '') ? value : (emptyDisplayColor || '');
            if (_disp) {
                if (_disp.startsWith('rgba')) {
                    var match = _disp.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                    if (match) {
                        r = parseInt(match[1]);
                        g = parseInt(match[2]);
                        b = parseInt(match[3]);
                        a = match[4] ? parseFloat(match[4]) : 1;
                        hexVal = '#' + r.toString(16).padStart(2,'0') + g.toString(16).padStart(2,'0') + b.toString(16).padStart(2,'0');
                    }
                } else if (_disp.startsWith('#')) {
                    hexVal = _disp.length === 4 ?
                        '#' + _disp[1]+_disp[1] + _disp[2]+_disp[2] + _disp[3]+_disp[3] : _disp;
                    r = parseInt(hexVal.substr(1,2), 16);
                    g = parseInt(hexVal.substr(3,2), 16);
                    b = parseInt(hexVal.substr(5,2), 16);
                } else if (_disp === 'transparent') {
                    a = 0;
                }
            }
            
            var hsv = rgbToHsv(r, g, b);
            var hue = Math.round(hsv.h);
            var sat = Math.round(hsv.s);
            var val = Math.round(hsv.v);
            var alphaPercent = Math.round(a * 100);
            
            var previewColor = a < 1 ? 'rgba('+r+','+g+','+b+','+a+')' : hexVal;
            var hueColor = 'hsl('+hue+',100%,50%)';
            var alphaGradient = 'linear-gradient(to right, transparent, '+hexVal+')';
            
            var html = '<div class="impulse-color-setting impulse-color-swatch-only" data-name="' + name + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>';
            html += '<div class="impulse-color-row">';
            html += '<div class="impulse-color-swatch" style="--swatch-color:' + previewColor + '"></div>';
            html += '<input type="hidden" name="' + name + '" value="' + (value || '') + '" class="impulse-color-text">';

            html += '<div class="impulse-color-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'" data-alpha="'+alphaPercent+'">';
            html += '<div class="impulse-picker-gradient" style="background-color:'+hueColor+'">';
            html += '<div class="impulse-picker-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div>';
            html += '</div>';
            html += '<div class="impulse-picker-sliders">';
            html += '<div class="impulse-picker-slider-row">';
            html += '<div class="impulse-picker-hue"><div class="impulse-picker-thumb" style="left:'+((hue/360)*100)+'%"></div></div></div>';
            html += '<div class="impulse-picker-slider-row">';
            html += '<div class="impulse-picker-alpha" style="--alpha-gradient:'+alphaGradient+'"><div class="impulse-picker-thumb" style="left:'+alphaPercent+'%"></div></div></div>';
            html += '</div>';
            html += '<div class="impulse-picker-tools">';
            html += '<div class="impulse-picker-hex"><input type="text" value="' + hexVal + '" placeholder="#000000"></div>';
            html += '<button type="button" class="impulse-picker-eyedropper" title="Pick color from screen"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.71 5.63l-2.34-2.34a1 1 0 00-1.41 0l-3.12 3.12-1.42-1.42-1.41 1.42 1.41 1.41-6.6 6.6a2 2 0 00-.57 1.2l-.67 4.03 4.03-.67a2 2 0 001.2-.57l6.6-6.6 1.41 1.41 1.42-1.41-1.42-1.42 3.13-3.13a1 1 0 000-1.41z"/></svg></button>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            return html;
        }

        

        
        function settingColorSwap(name1, name2, tip) {
            return '<button type="button" class="impulse-color-swap" data-c1="'
                 + name1 + '" data-c2="' + name2 + '" title="' + (tip || 'Swap colors')
                 + '" style="width:18px;height:26px;padding:0;background:transparent;'
                 + 'border:none;cursor:pointer;color:' + ImpC.muted + ';display:flex;'
                 + 'align-items:center;justify-content:center;flex-shrink:0;'
                 + 'transition:color 0.15s">'
                 + '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" '
                 + 'stroke="currentColor" stroke-width="2" stroke-linecap="round" '
                 + 'stroke-linejoin="round"><path d="M8 3 4 7l4 4"/><path d="M4 7h13"/>'
                 + '<path d="m16 21 4-4-4-4"/><path d="M20 17H7"/></svg></button>';
        }

        function hslToRgb(h, s, l) {
            h /= 360; s /= 100; l /= 100;
            var r, g, b;
            if (s === 0) {
                r = g = b = l;
            } else {
                function hue2rgb(p, q, t) {
                    if (t < 0) t += 1;
                    if (t > 1) t -= 1;
                    if (t < 1/6) return p + (q - p) * 6 * t;
                    if (t < 1/2) return q;
                    if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
                    return p;
                }
                var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
                var p = 2 * l - q;
                r = hue2rgb(p, q, h + 1/3);
                g = hue2rgb(p, q, h);
                b = hue2rgb(p, q, h - 1/3);
            }
            return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
        }

        function hsvToRgb(h, s, v) {
            h /= 360; s /= 100; v /= 100;
            var r, g, b;
            var i = Math.floor(h * 6);
            var f = h * 6 - i;
            var p = v * (1 - s);
            var q = v * (1 - f * s);
            var t = v * (1 - (1 - f) * s);
            switch (i % 6) {
                case 0: r = v; g = t; b = p; break;
                case 1: r = q; g = v; b = p; break;
                case 2: r = p; g = v; b = t; break;
                case 3: r = p; g = q; b = v; break;
                case 4: r = t; g = p; b = v; break;
                case 5: r = v; g = p; b = q; break;
            }
            return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
        }

        function rgbToHsv(r, g, b) {
            r /= 255; g /= 255; b /= 255;
            var max = Math.max(r, g, b), min = Math.min(r, g, b);
            var h, s, v = max;
            var d = max - min;
            s = max === 0 ? 0 : d / max;
            if (max === min) {
                h = 0;
            } else {
                switch (max) {
                    case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
                    case g: h = ((b - r) / d + 2) / 6; break;
                    case b: h = ((r - g) / d + 4) / 6; break;
                }
            }
            return { h: h * 360, s: s * 100, v: v * 100 };
        }

        function getResponsiveValue(settings, key, defaultVal, device) {
            device = device || window.impulseDevice || 'desktop';
            var debug = window.impulseDebug || false;
            var result;
            
            if (device === 'desktop') {
                result = settings[key] !== undefined ? settings[key] : defaultVal;
                if (debug) console.log('[getResponsiveValue]', key, 'desktop:', result, '(from base or default)');
                return result;
            }

            if (device === 'mobile') {
                if (settings[key + '_mobile'] !== undefined) {
                    result = settings[key + '_mobile'];
                    if (debug) console.log('[getResponsiveValue]', key, 'mobile:', result, '(from _mobile)');
                    return result;
                }
                if (settings[key + '_tablet'] !== undefined) {
                    result = settings[key + '_tablet'];
                    if (debug) console.log('[getResponsiveValue]', key, 'mobile:', result, '(fallback from _tablet)');
                    return result;
                }
                result = settings[key] !== undefined ? settings[key] : defaultVal;
                if (debug) console.log('[getResponsiveValue]', key, 'mobile:', result, '(fallback from base/default)');
                return result;
            }

            if (settings[key + '_tablet'] !== undefined) {
                result = settings[key + '_tablet'];
                if (debug) console.log('[getResponsiveValue]', key, 'tablet:', result, '(from _tablet)');
                return result;
            }
            result = settings[key] !== undefined ? settings[key] : defaultVal;
            if (debug) console.log('[getResponsiveValue]', key, 'tablet:', result, '(fallback from base/default)');
            return result;
        }

        function hasDeviceOverride(settings, key, device) {
            device = device || window.impulseDevice || 'desktop';
            if (device === 'desktop') return false;
            return settings[key + '_' + device] !== undefined;
        }

        function settingSliderR(name, label, settings, defaultVal, min, max, unit, inline, tip) {
            var value = getResponsiveValue(settings, name, defaultVal);
            return settingSlider(name, label, value, min, max, unit, inline, true, defaultVal, tip);
        }

        function settingMargins(settings) {
            var html = '<div class="impulse-margins-section">';
            html += '<div class="impulse-section-divider">Margin</div>';
            html += '<div class="impulse-margin-grid">';
            html += settingSliderR('margin_top', 'Top', settings, 0, 0, 100, 'px');
            html += settingSliderR('margin_right', 'Right', settings, 0, 0, 100, 'px');
            html += settingSliderR('margin_bottom', 'Bottom', settings, 0, 0, 100, 'px');
            html += settingSliderR('margin_left', 'Left', settings, 0, 0, 100, 'px');
            html += '</div></div>';
            return html;
        }

        function settingPadding(settings) {
            var html = '<div class="impulse-padding-section">';
            html += '<div class="impulse-section-divider">Padding</div>';
            html += '<div class="impulse-padding-grid">';
            html += settingSliderR('padding_top', 'Padding Top', settings, 0, 0, 100, 'px');
            html += settingSliderR('padding_right', 'Padding Right', settings, 0, 0, 100, 'px');
            html += settingSliderR('padding_bottom', 'Padding Bottom', settings, 0, 0, 100, 'px');
            html += settingSliderR('padding_left', 'Padding Left', settings, 0, 0, 100, 'px');
            html += '</div></div>';
            return html;
        }

        function settingBorder(prefix, settings, title) {
            title = title || 'Border';
            var pf = prefix || '';
            var borderWidth = settings[pf + 'border_width'] || 0;
            var borderColor = settings[pf + 'border_color'] || ''+ImpC.text+'';
            
            function isBorderEnabled(val) {
                if (val === undefined || val === null) return true; 
                if (val === false || val === '0' || val === 0) return false;
                return true;
            }
            var borderTop = isBorderEnabled(settings[pf + 'border_top']);
            var borderRight = isBorderEnabled(settings[pf + 'border_right']);
            var borderBottom = isBorderEnabled(settings[pf + 'border_bottom']);
            var borderLeft = isBorderEnabled(settings[pf + 'border_left']);

            
            
            var html = '<div class="impulse-section-divider impulse-divider-with-toggle">' + title
                + '<span style="flex:1;height:1px;background:var(--imp-panel)"></span>'
                + settingColorSwatchOnly(pf + 'border_color', borderColor)
                + '</div>';
            html += settingSliderR(pf + 'border_width', 'Width', settings, 0, 0, 10, 'px');
            
            html += '<div class="impulse-border-sides" data-prefix="' + pf + '" style="display:' + (parseInt(borderWidth) > 0 ? 'flex' : 'none') + ';gap:3px;margin-top:8px">';
            var sides = ['top', 'right', 'bottom', 'left'];
            var labels = ['Top', 'Right', 'Bottom', 'Left'];
            var sideValues = [borderTop, borderRight, borderBottom, borderLeft];
            for (var i = 0; i < 4; i++) {
                var side = sides[i];
                var checked = sideValues[i];
                html += '<button type="button" class="impulse-border-side-btn' + (checked ? ' active' : '') + '" data-side="' + side + '" style="flex:1">' + labels[i] + '</button>';
                html += '<input type="hidden" name="' + pf + 'border_' + side + '" value="' + (checked ? '1' : '0') + '">';
            }
            html += '</div>';
            return html;
        }
        
        function settingSlider(name, label, value, min, max, unit, inline, responsive, defaultVal, tip) {
            var cls = 'impulse-setting-row inline-slider';
            var displayValue = value;
            var dataUnit = unit !== undefined ? unit : 'px';
            var dataDefault = defaultVal !== undefined ? defaultVal : value;
            
            var isResponsive = responsive || isResponsiveSetting(name);
            var dataResponsive = isResponsive ? ' data-responsive="true"' : '';

            if (typeof value === 'object' && value !== null) {
                displayValue = value.desktop !== undefined ? value.desktop : (value.base !== undefined ? value.base : 0);
            }

            

            

            
            
            var _numDisplay = parseFloat(displayValue);
            if (!isNaN(_numDisplay) && _numDisplay > max) {

                

                

                if (dataUnit === '%' && _numDisplay > max * 2) {
                    displayValue = max;
                } else {
                    max = _numDisplay;
                }
            }

            var labelHtml = tip ? '<span data-tip="' + tip + '">' + label + '</span>' : label;
            var stepAttr = arguments[10] ? ' step="' + arguments[10] + '"' : ''; return '<div class="' + cls + '"' + dataResponsive + '><label>' + labelHtml + '</label><span class="impulse-slider-value">' + displayValue + dataUnit + '</span><div class="impulse-slider-row" data-unit="' + dataUnit + '"' + dataResponsive + '><input type="range" name="' + name + '" value="' + displayValue + '" min="' + min + '" max="' + max + '"' + stepAttr + ' data-default="' + dataDefault + '"></div></div>';
        }
        
        function settingImage(name, label, value) {
            var html = '<div class="impulse-setting-row impulse-image-setting" data-name="' + name + '">';
            html += '<label>' + label + '</label>';
            html += '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="' + name + '" style="' + (value ? 'display:none' : '') + '">Select</button>';
            html += '<input type="hidden" name="' + name + '" value="' + (value || '') + '">';
            if (value) {
                html += '<div class="impulse-image-preview"><button type="button" class="impulse-remove-image-btn" data-name="' + name + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button></div>';
            }
            html += '</div>';
            return html;
        }

        

        
        function settingTextReveal(settings) {
            var value     = settings.text_reveal || 'none';
            
            var stagger   = settings.text_reveal_stagger  !== undefined ? parseFloat(settings.text_reveal_stagger)  : 0.04;
            var duration  = settings.text_reveal_duration !== undefined ? parseFloat(settings.text_reveal_duration) : 0.8;

            var html = '<div class="impulse-section-divider">Text Reveal</div>';

            html += '<div class="impulse-setting-row">';
            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="text_reveal" style="display:flex;width:100%;gap:3px">';

            
            
            var presets = [{v:'words',l:'Words'},{v:'lines',l:'Lines'},{v:'chars',l:'Chars'},{v:'sweep',l:'Sweep'}];
            presets.forEach(function(p) {
                html += '<button type="button" data-value="' + p.v + '" class="' + (value === p.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + p.l + '</button>';
            });
            html += '<input type="hidden" name="text_reveal" value="' + value + '">';
            html += '</div></div>';

            var show = value !== 'none';
            html += '<div class="impulse-text-reveal-controls" style="display:' + (show ? 'block' : 'none') + '">';
            html += '<div class="impulse-margin-grid" style="margin-top:8px">';
            
            html += settingSlider('text_reveal_stagger', 'Stagger', stagger, 0, 0.2, 's', false, false, 0.04, undefined, 0.01);
            
            html += settingSlider('text_reveal_duration', 'Duration', duration, 0.2, 5, 's', false, false, 0.8, undefined, 0.1);
            html += '</div>';
            
            html += '<div style="display:flex;justify-content:flex-end;margin-top:8px">';
            html += '<svg class="impulse-text-reveal-preview-btn" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="cursor:pointer;opacity:0.6" title="Preview Text Reveal"><polygon points="6 3 20 12 6 21 6 3"/></svg>';
            html += '</div>';
            html += '</div>';
            return html;
        }

        function settingEntranceAnimation(settings, inlineExtra) {
            
            if (Impulse.pageSettings && (true)) return '';
            var value = settings.entrance_animation || 'none';
            var intensity = settings.entrance_intensity !== undefined ? parseInt(settings.entrance_intensity) : 50;
            
            var duration = settings.animation_duration !== undefined ? parseFloat(settings.animation_duration) : 0.6;
            var unveilDir = settings.unveil_direction || 'up';
            
            var html = '<div class="impulse-section-divider">Entrance Animation</div>';

            html += '<div class="impulse-setting-row">';
            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="entrance_animation" data-toggleable="1" style="display:flex;width:100%;gap:3px">';
            var presets = [{v:'emerge',l:'Emerge'},{v:'surface',l:'Surface'},{v:'unveil',l:'Unveil'},{v:'resolve',l:'Resolve'}];
            presets.forEach(function(p) {
                html += '<button type="button" data-value="' + p.v + '" class="' + (value === p.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + p.l + '</button>';
            });
            html += '<input type="hidden" name="entrance_animation" value="' + value + '">';
            html += '</div></div>';

            var show = value !== 'none';
            html += '<div class="impulse-entrance-controls" style="display:' + (show ? 'block' : 'none') + '">';

            html += '<div class="impulse-entrance-direction" style="display:' + (value === 'unveil' ? 'block' : 'none') + ';margin-top:8px">';
            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="unveil_direction" style="display:flex;width:100%;gap:3px">';
            [{v:'up',l:'Up'},{v:'down',l:'Down'},{v:'left',l:'Left'},{v:'right',l:'Right'}].forEach(function(d) {
                html += '<button type="button" data-value="' + d.v + '" class="' + (unveilDir === d.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + d.l + '</button>';
            });
            html += '<input type="hidden" name="unveil_direction" value="' + unveilDir + '">';
            html += '</div></div>';

            html += '<div class="impulse-margin-grid" style="margin-top:8px">';
            html += '<div class="impulse-entrance-intensity" style="' + (value !== 'unveil' ? '' : 'display:none') + '">';
            html += settingSlider('entrance_intensity', 'Intensity', intensity, 10, 100, '', false, false, 50);
            html += '</div>';
            html += settingSlider('animation_duration', 'Duration', duration, 0.2, 5, 's', false, false, 0.6, undefined, 0.1);
            html += '</div>';

            
            
            html += '<div style="display:flex;align-items:center;justify-content:' + (inlineExtra ? 'space-between' : 'flex-end') + ';margin-top:8px">';
            html += (inlineExtra || '');
            html += '<svg class="impulse-animation-preview-btn" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="cursor:pointer;opacity:0.6" title="Preview Animation"><polygon points="6 3 20 12 6 21 6 3"/></svg>';
            html += '</div>';
            
            html += '</div>';
            return html;
        }

        
        
        function bgShapeSlider(idx, prop, label, value, min, max, unit) {
            return '<div class="impulse-setting-row inline-slider">' +
                '<label>' + label + '</label>' +
                '<span class="impulse-slider-value">' + value + unit + '</span>' +
                '<div class="impulse-slider-row" data-unit="' + unit + '">' +
                '<input type="range" class="impulse-bg-shape-ctrl" data-idx="' + idx + '" data-prop="' + prop + '" data-unit="' + unit + '" min="' + min + '" max="' + max + '" value="' + value + '">' +
                '</div></div>';
        }

        

        
        
        function settingBgShapes(settings) {
            var device = window.impulseDevice || 'desktop';
            var shapes = [];
            try { shapes = JSON.parse(settings.bg_shapes || '[]'); } catch(e) { shapes = []; }
            if (!Array.isArray(shapes)) shapes = [];

            var html = '<div class="impulse-section-divider impulse-divider-with-toggle">';
            html += '<span>Background Shapes</span>';
            html += '<span class="impulse-divider-line" style="flex:1;height:1px;background:' + ImpC.panel + '"></span>';
            html += '<div class="impulse-btn-group" style="flex-shrink:0">';
            html += '<button type="button" class="impulse-bg-shape-add">+ Add</button>';
            html += '</div></div>';
            html += '<div class="impulse-bg-shapes-list">';

            
            function anchorIcon(a) {
                var pts = { tl:[3,3], tr:[13,3], bl:[3,13], br:[13,13], cc:[8,8] };
                var p = pts[a] || pts.cc;
                return '<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1">' +
                    '<rect x="2" y="2" width="12" height="12" rx="1"/>' +
                    '<circle cx="' + p[0] + '" cy="' + p[1] + '" r="1.6" fill="currentColor" stroke="none"/>' +
                    '</svg>';
            }
            var anchorOpts = ['tl','tr','cc','bl','br'];

            shapes.forEach(function(shape, idx) {
                var anchor  = getDeviceVal(shape, 'anchor',   device, shape.anchor || 'cc');
                var ox      = getDeviceVal(shape, 'ox',       device, shape.ox !== undefined ? shape.ox : 0);
                var oy      = getDeviceVal(shape, 'oy',       device, shape.oy !== undefined ? shape.oy : 0);
                var sizePct = getDeviceVal(shape, 'size_pct', device, shape.size_pct !== undefined ? shape.size_pct : 30);
                var op      = getDeviceVal(shape, 'opacity',  device, shape.opacity !== undefined ? shape.opacity : 100);
                var rot     = getDeviceVal(shape, 'rotation', device, shape.rotation || 0);
                var vis     = getDeviceVal(shape, 'visible',  device, shape.visible !== false);
                var flipped = getDeviceVal(shape, 'flip_h',   device, shape.flip_h || false);

                html += '<div class="impulse-bg-shape-item" data-idx="' + idx + '">';

                html += '<div class="impulse-bg-shape-head">';
                html += '<svg viewBox="' + escapeHtml(shape.viewbox || '0 0 24 24') + '" width="18" height="18" fill="' + escapeHtml((shape.colors && shape.colors[0]) || shape.color || ImpC.muted) + '" stroke="none">' + (shape.svg || '') + '</svg>';
                html += '<span style="flex:1;font-size:11px;color:#ccc;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escapeHtml(shape.name || 'Shape ' + (idx+1)) + '</span>';
                html += '<button type="button" class="impulse-bg-shape-remove" data-idx="' + idx + '" title="Remove" style="background:none;border:none;cursor:pointer;padding:2px;color:#666"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                html += '</div>';

                html += '<div style="display:flex;align-items:center;gap:6px;margin-top:8px">';
                html += '<span style="font-size:11px;color:#888;flex:0 0 auto">Anchor</span>';
                html += '<div class="impulse-btn-group" style="display:flex;flex:1;gap:2px">';
                anchorOpts.forEach(function(a) {
                    var active = (anchor === a) ? ' active' : '';
                    html += '<button type="button" class="impulse-bg-shape-anchor-btn' + active + '" data-anchor="' + a + '" data-idx="' + idx + '" style="flex:1;height:22px;padding:0;display:flex;align-items:center;justify-content:center" title="' + a.toUpperCase() + '">' + anchorIcon(a) + '</button>';
                });
                html += '</div></div>';

                

                
                html += '<div class="impulse-margin-grid" style="margin-top:8px">';
                html += bgShapeSlider(idx, 'size_pct', 'Size', sizePct, 5, 100, '%');
                html += bgShapeSlider(idx, 'rotation', 'Rotation', rot, -180, 180, '°');
                html += bgShapeSlider(idx, 'ox', 'Offset X', Math.round(ox), -50, 50, '%');
                html += bgShapeSlider(idx, 'oy', 'Offset Y', Math.round(oy), -50, 50, '%');
                html += bgShapeSlider(idx, 'opacity', 'Opacity', op, 0, 100, '%');
                html += '<div></div>';
                html += '</div>';

                

                

                
                html += '<div style="display:flex;gap:6px;align-items:center;margin-top:8px">';
                var colors = shape.colors || [shape.color || '#999999'];
                colors.forEach(function(c, ci) {
                    html += '<div class="impulse-color-row impulse-bg-shape-color-row" style="position:relative" data-idx="' + idx + '" data-cidx="' + ci + '">';
                    html += '<div class="impulse-color-swatch impulse-bg-shape-color" data-idx="' + idx + '" data-cidx="' + ci + '" style="--swatch-color:' + escapeHtml(c) + '" title="Color ' + (ci+1) + '"></div>';
                    html += '<input type="hidden" class="impulse-color-text impulse-bg-shape-color-text" data-idx="' + idx + '" data-cidx="' + ci + '" value="' + escapeHtml(c) + '">';
                    html += '</div>';
                });
                html += '<div style="flex:1"></div>';
                html += '<div class="impulse-btn-group">';
                html += '<button type="button" class="impulse-bg-shape-flip' + (flipped ? ' active' : '') + '" data-idx="' + idx + '" style="width:26px;height:26px;padding:0" title="Flip horizontal"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3"/><path d="M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3"/><line x1="12" y1="20" x2="12" y2="4"/></svg></button>';
                html += '</div></div>';

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

            html += '</div>'; 
            html += '<textarea name="bg_shapes" style="display:none">' + escapeHtml(JSON.stringify(shapes)) + '</textarea>';

            return html;
        }
        
        function getDeviceVal(obj, key, device, fallback) {
            if (device !== 'desktop') {
                var dk = key + '_' + device;
                if (obj[dk] !== undefined && obj[dk] !== null && obj[dk] !== '') return obj[dk];
            }
            return obj[key] !== undefined && obj[key] !== null ? obj[key] : fallback;
        }
        
        function escapeHtml(str) {
            if (str == null) return '';
            return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }

        

        

        function renderAddonRow(addon, i, open) {
            var typeLabel = {checkbox:'Checkbox', text:'Text', select:'Select'};
            var t   = addon.type || 'checkbox';
            var ml  = !!addon.multiline;
            var inp = 'width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;padding:0 8px;box-sizing:border-box';
            var html = '<div class="block-addon-row" data-idx="' + i + '" style="border:1px solid '+ImpC.panel+';border-radius:3px;margin-bottom:4px">';
            
            html += '<div class="block-addon-row-hdr" style="display:flex;align-items:center;padding:6px 8px;cursor:pointer;gap:6px">';
            html += '<svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="'+ImpC.dim+'" stroke-width="2.5" style="flex-shrink:0;transition:transform 0.15s' + (open ? ';transform:rotate(180deg)' : '') + '"><polyline points="6,9 12,15 18,9"/></svg>';
            html += '<span class="ba-row-label" style="flex:1;font-size:11px;color:' + (addon.name ? ''+ImpC.text+'' : ''+ImpC.dim+'') + '">' + escapeHtml(addon.name || 'Untitled field') + '</span>';
            html += '<button type="button" class="block-addon-remove" data-idx="' + i + '" style="width:26px;height:26px;background:none;border:none;color:'+ImpC.dim+';cursor:pointer;font-size:16px;line-height:1;padding:0;flex-shrink:0">&times;</button>';
            html += '</div>';
            if (open) {
                html += '<div class="block-addon-body" style="padding:8px;border-top:1px solid '+ImpC.panel+'">';
                
                html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Name</div>';
                html += '<input type="text" class="ba-name" data-idx="' + i + '" value="' + escapeHtml(addon.name || '') + '" placeholder="e.g. Gift wrap" style="' + inp + '"></div>';
                
                html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Type</div>';
                html += '<div style="display:flex;gap:3px">';
                ['checkbox','text','select'].forEach(function(tp) {
                    html += '<button type="button" class="impulse-btn-sm ba-type' + (t===tp?' active':'') + '" data-idx="' + i + '" data-type="' + tp + '" style="flex:1;height:26px;font-size:10px">' + typeLabel[tp] + '</button>';
                });
                html += '</div>';
                if (t === 'text') {
                    html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#888;cursor:pointer;margin-top:5px">';
                    html += '<input type="checkbox" class="ba-multiline" data-idx="' + i + '"' + (ml ? ' checked' : '') + ' style="width:13px;height:13px"> Multi-line</label>';
                }
                html += '</div>';
                
                html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Price <span style="color:'+ImpC.dim+'">(0 = free)</span></div>';
                html += '<div style="display:flex;gap:3px;align-items:center">';
                html += '<input type="text" inputmode="decimal" class="ba-price" data-idx="' + i + '" value="' + (parseFloat(addon.price||0) || 0) + '" placeholder="0" style="flex:1;' + inp + '">';
                html += '<button type="button" class="impulse-btn-sm ba-ptype' + (addon.price_type!=='percent'?' active':'') + '" data-idx="' + i + '" data-ptype="flat" style="width:26px;height:26px;padding:0;font-size:11px">$</button>';
                html += '<button type="button" class="impulse-btn-sm ba-ptype' + (addon.price_type==='percent'?' active':'') + '" data-idx="' + i + '" data-ptype="percent" style="width:26px;height:26px;padding:0;font-size:11px">%</button>';
                html += '</div></div>';
                
                html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer;margin-bottom:8px">';
                html += '<input type="checkbox" class="ba-required" data-idx="' + i + '"' + (addon.required?' checked':'') + ' style="width:13px;height:13px"> Required</label>';
                
                if (t === 'select') {
                    var opts = Array.isArray(addon.options) ? addon.options : [];
                    html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Options</div>';
                    html += '<div class="ba-options-list" data-idx="' + i + '" style="margin-bottom:4px">';
                    opts.forEach(function(opt, oi) {
                        html += '<div class="ba-option-row" style="display:flex;gap:4px;margin-bottom:3px">';
                        html += '<input type="text" class="ba-option-val" value="' + escapeHtml(opt) + '" placeholder="Option ' + (oi+1) + '" style="flex:1;' + inp + '">';
                        html += '<button type="button" class="ba-option-remove" style="width:26px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:#666;cursor:pointer;font-size:14px;flex-shrink:0">&times;</button>';
                        html += '</div>';
                    });
                    html += '</div>';
                    html += '<button type="button" class="ba-option-add" data-idx="' + i + '" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:#888;font-size:11px;cursor:pointer">+ Add Option</button>';
                    html += '</div>';
                }
                
                var scopeAll = !addon.product_id;
                html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Show on</div>';
                html += '<div style="display:flex;gap:3px' + (!scopeAll?';margin-bottom:4px':'') + '">';
                html += '<button type="button" class="impulse-btn-sm ba-scope' + (scopeAll?' active':'') + '" data-idx="' + i + '" data-scope="all" style="flex:1;height:26px;font-size:10px">All Products</button>';
                html += '<button type="button" class="impulse-btn-sm ba-scope' + (!scopeAll?' active':'') + '" data-idx="' + i + '" data-scope="specific" style="flex:1;height:26px;font-size:10px">Specific</button>';
                html += '</div>';
                if (!scopeAll) {
                    var pname = addon.product_name || ('Product #' + addon.product_id);
                    html += '<button type="button" class="ba-scope-pick" data-idx="' + i + '" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;cursor:pointer;text-align:left;padding:0 8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(pname) + '</button>';
                }
                html += '</div>';
                html += '</div>'; 
            }
            html += '</div>'; 
            return html;
        }

        function getBlockAddons() {
            try { return JSON.parse($('#block-addons-json').val() || '[]'); } catch(e) { return []; }
        }
        function saveBlockAddons(addons) {
            $('#block-addons-json').val(JSON.stringify(addons));
            clearTimeout(window._baTimer);
            window._baTimer = setTimeout(function() { autoSaveAndRefresh(); }, 400);
        }
        function rebuildAddonList(addons) {
            var html = '';
            if (!addons.length) {
                html = '<div style="font-size:11px;color:'+ImpC.dim+';text-align:center;padding:10px 0">No add-on fields yet.</div>';
            } else {
                var openIdx = (window._blockAddonOpenIdx !== undefined) ? window._blockAddonOpenIdx : -1;
                addons.forEach(function(a, i) { html += renderAddonRow(a, i, openIdx === i); });
            }
            $('#block-addons-list').html(html);
        }

        function buildAddonsSection(settings) {
            var blockAddons = Array.isArray(settings.addons) ? settings.addons : [];
            window._blockAddonOpenIdx = -1;
            var html = '<div class="impulse-section-divider">Add-Ons</div>';
            html += '<input type="hidden" name="addons_json" id="block-addons-json" value="' + escapeHtml(JSON.stringify(blockAddons)) + '">';
            html += '<div id="block-addons-list">';
            if (!blockAddons.length) {
                html += '<div style="font-size:11px;color:'+ImpC.dim+';text-align:center;padding:10px 0">No add-on fields yet.</div>';
            } else {
                blockAddons.forEach(function(a, i) { html += renderAddonRow(a, i, false); });
            }
            html += '</div>';
            html += '<button type="button" id="block-addon-add" class="impulse-btn-sm" style="width:100%;height:26px;margin-top:6px">+ Add Field</button>';
            return html;
        }

        function buildCardDesignSettings(settings, showContainerWidth, sectionBg, showSectionColor, elementsData) {
            var cardDesign = settings.card_design || {};
            var defaults = {
                elements: ['image', 'title', 'price', 'add_to_cart', 'sale_badge', 'featured_badge'],
                card: { background: '#ffffff', border_color: ''+ImpC.text+'', border_width: 1, border_radius: 8, shadow: 'small' },
                image: { aspect_ratio: 'square', border_radius: 8 },
                title: { font_size: 16, font_weight: '600', color: ''+ImpC.surface2+'', lines: 2 },
                price: { font_size: 18, font_weight: '700', color: '', sale_color: '#666666' }, 
                add_to_cart: { bg_color: ''+ImpC.surface2+'', text_color: '#ffffff', border_radius: 6, full_width: true, button_text: 'Add to Cart', font_size: 14, font_weight: '500' },
                sale_badge: { bg_color: ''+ImpC.surface2+'', featured_bg_color: ''+ImpC.surface2+'', text_color: '#ffffff', text: 'Sale', featured_text: 'Featured' },
                description: { font_size: 13, color: '#666666', lines: 2 }
            };

            var d = $.extend(true, {}, defaults, cardDesign);
            if (!Array.isArray(d.elements)) d.elements = defaults.elements;
            
            if (!d.price.color) d.price.color = d.title.color || ''+ImpC.surface2+'';
            
            var html = '';
            var device = window.impulseDevice || 'desktop';
            var sourceIsQuery = (settings.source || 'query') === 'query';
            
            var displayMode = (showSectionColor === true) ? (settings.display_mode || 'grid') : (showSectionColor === 'carousel' ? 'carousel' : 'grid');
            var isGrid = showSectionColor === true && displayMode === 'grid';
            var isCarousel = (showSectionColor === true && (displayMode === 'carousel' || displayMode === 'single')) || showSectionColor === 'carousel';

            var showModalTab = (showSectionColor === true); 

            var gapKey, gapValue, maxWidthValue;
            if (isGrid) {
                gapKey = device === 'desktop' ? 'gap' : 'gap_' + device;
                var gapDefault = device === 'desktop' ? 10 : 5;
                gapValue = settings[gapKey] !== undefined ? settings[gapKey] : gapDefault;
                maxWidthValue = settings.section_max_width !== undefined ? settings.section_max_width : 1200;
            } else if (showContainerWidth) {
                
            } else if (isCarousel) {
                
                gapKey = device === 'desktop' ? 'gap' : 'gap_' + device;
                var gapDefault = device === 'desktop' ? 10 : 5;
                gapValue = settings[gapKey] !== undefined ? settings[gapKey] : gapDefault;
                maxWidthValue = settings.section_max_width !== undefined ? settings.section_max_width : 1200;
            }

            if (showSectionColor === true) {
                html += '<div class="impulse-btn-group" data-name="display_mode" style="display:flex;width:100%;gap:5px;margin-bottom:6px">';
                [{v:'grid',l:'Grid'},{v:'menu',l:'Menu'},{v:'carousel',l:'Carousel'}].forEach(function(m) {
                    html += '<button type="button" data-value="' + m.v + '"' + (displayMode === m.v ? ' class="active"' : '') + ' style="flex:1;height:26px;font-size:11px">' + m.l + '</button>';
                });
                html += '<input type="hidden" name="display_mode" value="' + displayMode + '">';
                html += '</div>';

                

                

                
                
                if (displayMode === 'menu') {
                    var mChk = function(k, def) { var v = settings[k]; if (v === undefined) return def; return v === true || v === '1' || v === 1; };

                    var mSrc = settings.source || 'query';
                    html += '<div class="impulse-btn-group" data-name="source" style="display:flex;width:100%;gap:5px;margin-bottom:6px">';
                    [{v:'query',l:'Query'},{v:'manual',l:'Specific'}].forEach(function(s) {
                        html += '<button type="button" data-value="' + s.v + '"' + (mSrc === s.v ? ' class="active"' : '') + ' style="flex:1;height:26px;font-size:11px">' + s.l + '</button>';
                    });
                    html += '<input type="hidden" name="source" value="' + mSrc + '">';
                    html += '</div>';

                    var mQType = settings.query_type || 'newest';
                    html += '<div class="impulse-products-query" style="' + (mSrc !== 'query' ? 'display:none;' : '') + 'margin-bottom:6px">';
                    html += '<div class="impulse-btn-group" data-name="query_type" style="display:flex;width:100%;gap:5px;margin-bottom:6px">';
                    [{v:'newest',l:'Recent'},{v:'featured',l:'Featured'},{v:'sale',l:'Sale'},{v:'category',l:'Category'}].forEach(function(q) {
                        html += '<button type="button" data-value="' + q.v + '"' + (mQType === q.v ? ' class="active"' : '') + ' style="flex:1;height:26px;font-size:10px">' + q.l + '</button>';
                    });
                    html += '<input type="hidden" name="query_type" value="' + mQType + '">';
                    html += '</div>';
                    var mCats = (window.Impulse && Impulse.categories) || [];
                    html += '<div class="impulse-query-category-row" style="margin-bottom:6px;' + (mQType !== 'category' ? 'display:none' : '') + '">';
                    html += '<select name="category_id" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+'">';
                    html += '<option value="">All categories</option>';
                    mCats.forEach(function(cat) {
                        html += '<option value="' + cat.id + '"' + (settings.category_id == cat.id ? ' selected' : '') + '>' + escapeHtml(cat.name) + '</option>';
                    });
                    html += '</select></div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSlider('count', 'Items to show', settings.count || 12, 1, 50, '');
                    html += '<div></div>';
                    html += '</div>';
                    html += '</div>'; 

                    html += '<div class="impulse-products-manual" style="' + (mSrc !== 'manual' ? 'display:none;' : '') + 'margin-bottom:6px">';
                    var mIds = (settings.product_ids || '').toString().split(',').filter(function(x) { return x.trim(); });
                    html += '<div class="impulse-manual-products-list" style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px">';
                    if (mIds.length) {
                        mIds.forEach(function(pid) {
                            html += '<span class="impulse-manual-product-chip" data-id="' + pid.trim() + '" style="display:inline-flex;align-items:center;gap:4px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;padding:2px 6px;font-size:10px;color:'+ImpC.text+'">#' + pid.trim() + '<span class="impulse-manual-product-remove" title="Remove" style="display:inline-flex;cursor:pointer;flex-shrink:0"><svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></span></span>';
                        });
                    } else {
                        html += '<span style="font-size:11px;color:'+ImpC.dim+';padding:2px 0">No products selected</span>';
                    }
                    html += '</div>';
                    html += '<input type="hidden" name="product_ids" value="' + escapeHtml(settings.product_ids || '') + '">';
                    html += '<button type="button" id="impulse-select-products" style="width:100%;height:26px;padding:0 12px;background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;box-sizing:border-box;display:flex;align-items:center;justify-content:center;gap:4px">';
                    html += '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Select Products</button>';
                    html += '</div>'; 

                    html += '<div class="impulse-section-divider">Connector</div>';
                    var mSep = settings.pl_separator || 'dots';
                    html += '<div class="impulse-btn-group-rows" style="display:flex;flex-direction:column;gap:3px">';
                    html += '<div class="impulse-btn-group" data-name="pl_separator" data-toggleable="1" style="display:flex;width:100%;gap:3px">';
                    [{v:'dashed',l:'Dashed'},{v:'solid',l:'Line'},{v:'fade',l:'Fade'},{v:'dots',l:'Dots'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (mSep === o.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '</div>';
                    html += '<div class="impulse-btn-group" data-name="pl_separator" data-toggleable="1" style="display:flex;width:100%;gap:3px">';
                    [{v:'wave',l:'Wave'},{v:'zigzag',l:'Zigzag'},{v:'pulse',l:'Pulse'},{v:'shimmer',l:'Shimmer'}].forEach(function(o) {
                        html += '<button type="button" data-value="' + o.v + '" class="' + (mSep === o.v ? 'active' : '') + '" style="flex:1;height:26px;padding:0;font-size:11px;box-sizing:border-box">' + o.l + '</button>';
                    });
                    html += '</div>';
                    html += '<input type="hidden" name="pl_separator" value="' + mSep + '">';
                    html += '</div>';

                    var mDesc = mChk('menu_show_desc', true);
                    var mThumb = mChk('menu_show_thumb', false);
                    var mBtn = mChk('menu_show_button', true);
                    var mDivOn = (settings.pl_show_divider === undefined) ? true : (settings.pl_show_divider === '1' || settings.pl_show_divider === 1 || settings.pl_show_divider === true);
                    var _cbS = 'display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.muted+';cursor:pointer';
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:12px">';
                    html += '<label style="'+_cbS+'"><input type="checkbox" name="menu_show_desc"' + (mDesc ? ' checked' : '') + ' style="margin:0">Description</label>';
                    html += '<label style="'+_cbS+'">Thumbnail<input type="checkbox" name="menu_show_thumb"' + (mThumb ? ' checked' : '') + ' style="margin:0"></label>';
                    html += '</div>';
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">';
                    html += '<label style="'+_cbS+'"><input type="checkbox" name="menu_show_button" id="menu-show-button-cb"' + (mBtn ? ' checked' : '') + ' style="margin:0">Order button</label>';
                    html += '<label style="'+_cbS+'">Divider<input type="checkbox" name="pl_show_divider" id="menu-divider-cb"' + (mDivOn ? ' checked' : '') + ' style="margin:0"></label>';
                    html += '</div>';

                    html += '<div id="menu-btnlabel-row" class="impulse-inline-right" style="margin-top:10px;' + (mBtn ? '' : 'display:none') + '"><label style="font-size:11px">Button</label>';
                    html += '<input type="text" name="menu_btn_label" value="' + escapeHtml(settings.menu_btn_label || 'Add to cart') + '" placeholder="Add to cart" style="width:130px;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;padding:0 8px;box-sizing:border-box"></div>';

                    var _swVisIdx = 0;
                    var _swCell = function(label, name, def, cls, hidden) {
                        var alignVal = 'center';
                        if (!hidden) {
                            var _c = _swVisIdx % 3;
                            alignVal = (_c === 0) ? 'flex-start' : (_c === 2) ? 'flex-end' : 'center';
                            _swVisIdx++;
                        }
                        return '<div class="impulse-menu-sw' + (cls ? ' ' + cls : '') + '" style="flex-direction:column;align-items:' + alignVal + ';gap:4px;display:' + (hidden ? 'none' : 'flex') + '"><label style="font-size:11px;color:#888">' + label + '</label>' + settingColorSwatchOnly(name, settings[name] || def) + '</div>';
                    };
                    html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px 6px;margin-top:12px">';
                    html += _swCell('Title',       'pl_title_color',  '#1d2327');
                    html += _swCell('Price',       'pl_price_color',  '#1d2327');
                    html += _swCell('Description', 'pl_desc_color',   '#888888');
                    html += _swCell('Connector',   'pl_sep_color',    '#cccccc');
                    html += _swCell('Divider',     'pl_border_color', '#e0e0e0', 'menu-sw-divider', !mDivOn);
                    html += _swCell('Button',      'menu_btn_bg',     '#1d2327', 'menu-sw-btn', !mBtn);
                    html += _swCell('Btn Text',    'menu_btn_color',  '#ffffff', 'menu-sw-btn', !mBtn);
                    html += '</div>';

                    

                    html += '<div class="impulse-margin-grid" style="margin-top:10px">';
                    html += settingSliderR('pl_title_size', 'Title', settings, 16, 12, 28, 'px', true);
                    html += settingSliderR('pl_price_size', 'Price', settings, 16, 12, 28, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('pl_desc_size', 'Description', settings, 13, 10, 20, 'px', true);
                    html += settingSliderR('pl_spacing', 'Spacing', settings, 16, 4, 40, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('section_max_width', 'Max width', settings, 800, 200, 1600, 'px');
                    html += settingSliderR('menu_thumb_size', 'Thumb size', settings, 44, 24, 160, 'px', true);
                    html += '</div>';
                    html += '<div class="impulse-margin-grid">';
                    html += settingSliderR('menu_btn_radius', 'Button radius', settings, 6, 0, 24, 'px');
                    html += '<div></div>';
                    html += '</div>';

                    return html;
                }
            }

            
            
            if (isGrid || isCarousel) {
                var srcVal = settings.source || 'query';
                html += '<div class="impulse-btn-group" data-name="source" style="display:flex;width:100%;gap:5px;margin-bottom:6px">';
                [{v:'query',l:'Query'},{v:'manual',l:'Specific'}].forEach(function(s) {
                    html += '<button type="button" data-value="' + s.v + '"' + (srcVal === s.v ? ' class="active"' : '') + ' style="flex:1;height:26px;font-size:11px">' + s.l + '</button>';
                });
                html += '<input type="hidden" name="source" value="' + srcVal + '">';
                html += '</div>';

                html += '<div class="impulse-products-query" style="' + (srcVal !== 'query' ? 'display:none;' : '') + 'margin-bottom:6px">';

                var colCount = device === 'mobile' ? (parseInt(settings.columns_mobile) || 1)
                             : device === 'tablet' ? (parseInt(settings.columns_tablet) || 2)
                             : (parseInt(settings.columns) || 4);
                
                var colMax = device === 'mobile' ? 2 : device === 'tablet' ? 3 : 6;
                colCount = Math.min(colCount, colMax);
                
                var qType = settings.query_type || 'newest';
                html += '<div class="impulse-btn-group" data-name="query_type" style="display:flex;width:100%;gap:5px;margin-bottom:6px">';
                [{v:'newest',l:'Recent'},{v:'featured',l:'Featured'},{v:'sale',l:'Sale'},{v:'category',l:'Category'}].forEach(function(q) {
                    html += '<button type="button" data-value="' + q.v + '"' + (qType === q.v ? ' class="active"' : '') + ' style="flex:1;height:26px;font-size:10px">' + q.l + '</button>';
                });
                html += '<input type="hidden" name="query_type" value="' + qType + '">';
                html += '</div>';
                
                var impulseCategories = Impulse.categories || [];
                html += '<div class="impulse-query-category-row" style="margin-bottom:6px;' + (qType !== 'category' ? 'display:none' : '') + '">';
                html += '<select name="category_id" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+'">';
                html += '<option value="">All categories</option>';
                impulseCategories.forEach(function(cat) {
                    html += '<option value="' + cat.id + '"' + (settings.category_id == cat.id ? ' selected' : '') + '>' + escapeHtml(cat.name) + '</option>';
                });
                html += '</select>';
                html += '</div>';
                
                html += '<div class="impulse-inline-right"' + (isCarousel ? ' style="display:none"' : '') + '>';
                html += '<label style="font-size:11px">Columns</label>';
                html += '<div class="impulse-btn-group" data-name="columns" style="gap:5px">';
                for (var ci = 1; ci <= colMax; ci++) {
                    html += '<button type="button" class="' + (colCount === ci ? 'active' : '') + '" data-value="' + ci + '" style="height:26px;width:26px;padding:0;font-size:11px;box-sizing:border-box">' + ci + '</button>';
                }
                html += '<input type="hidden" name="columns" value="' + colCount + '">';
                html += '</div></div>';
                html += '</div>'; 

                html += '<div class="impulse-products-manual" style="' + (srcVal !== 'manual' ? 'display:none;' : '') + 'margin-bottom:6px">';
                
                var manualIds = (settings.product_ids || '').toString().split(',').filter(function(x) { return x.trim(); });
                html += '<div class="impulse-manual-products-list" style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px">';
                if (manualIds.length) {
                    manualIds.forEach(function(pid) {
                        html += '<span class="impulse-manual-product-chip" data-id="' + pid.trim() + '" style="display:inline-flex;align-items:center;gap:4px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;padding:2px 6px;font-size:10px;color:'+ImpC.text+'">#' + pid.trim();
                        html += '<span class="impulse-manual-product-remove" title="Remove" style="display:inline-flex;cursor:pointer;flex-shrink:0"><svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></span>';
                        html += '</span>';
                    });
                } else {
                    html += '<span style="font-size:11px;color:'+ImpC.dim+';padding:2px 0">No products selected</span>';
                }
                html += '</div>';
                html += '<input type="hidden" name="product_ids" value="' + escapeHtml(settings.product_ids || '') + '">';
                html += '<button type="button" id="impulse-select-products" style="width:100%;height:26px;padding:0 12px;background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;box-sizing:border-box;display:flex;align-items:center;justify-content:center;gap:4px">';
                html += '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Select Products</button>';
                html += '</div>'; 
            }

            var hasBorder = (parseInt(d.card.border_width) > 0);
            var hasShadow = !!(d.card.shadow && d.card.shadow !== '');
            html += '<div style="display:flex;gap:5px;margin-top:6px">';
            html += '<button type="button" class="impulse-pcard-toggle' + (hasBorder ? ' active' : '') + '" data-field="card_design_card_border_width" data-on="1" data-off="0" style="flex:1;height:26px;font-size:11px">Border</button>';
            html += '<input type="hidden" name="card_design_card_border_width" value="' + (hasBorder ? d.card.border_width : 0) + '">';
            html += '<button type="button" class="impulse-pcard-toggle' + (hasShadow ? ' active' : '') + '" data-field="card_design_card_shadow" data-on="small" data-off="" style="flex:1;height:26px;font-size:11px">Shadow</button>';
            html += '<input type="hidden" name="card_design_card_shadow" value="' + (hasShadow ? d.card.shadow : '') + '">';
            html += '</div>';

            
            if (!showContainerWidth) {
                
                var carColMax = device === 'mobile' ? 2 : device === 'tablet' ? 3 : 6;
                var visCountShared = device === 'mobile' ? (parseInt(settings.columns_mobile) || 2)
                                   : device === 'tablet' ? (parseInt(settings.columns_tablet) || 2)
                                   : (parseInt(settings.carousel_cards) || parseInt(settings.columns) || 4);
                visCountShared = Math.min(visCountShared, carColMax);
                var isCarouselShared2 = (settings.display_mode === 'carousel');
                var isScrollShared2 = isCarouselShared2 && ((settings.carousel_mode === 'scroll'));
                html += '<div class="impulse-inline-right" style="margin-top:6px' + (!isCarouselShared2 || isScrollShared2 ? ';display:none' : '') + '" id="ppc-maxcards-row">';
                html += '<label style="font-size:11px">Cards</label>';
                html += '<div class="impulse-btn-group" data-name="carousel_cards" style="gap:5px">';
                var carMin = device === 'desktop' ? 2 : 1;
                for (var ci2 = carMin; ci2 <= carColMax; ci2++) {
                    html += '<button type="button" class="' + (visCountShared === ci2 ? 'active' : '') + '" data-value="' + ci2 + '" style="height:26px;width:26px;padding:0;font-size:11px">' + ci2 + '</button>';
                }
                html += '<input type="hidden" name="carousel_cards" value="' + visCountShared + '">';
                html += '</div></div>';
            }

            if (!showContainerWidth) {
                var carouselModeShared = settings.carousel_mode || 'snap';
                if (carouselModeShared === 'slide') carouselModeShared = 'snap';
                if (carouselModeShared === 'fade' || carouselModeShared === 'card_flip') carouselModeShared = 'snap';
                var isCarouselModeShared = (settings.display_mode === 'carousel');
                html += '<div style="margin-top:6px' + (isCarouselModeShared ? '' : ';display:none') + '" id="ppc-slidescroll-row">';
                html += '<div class="impulse-btn-group" data-name="carousel_mode" style="display:grid;grid-template-columns:1fr 1fr;gap:5px">';
                [{v:'snap',l:'Slide'},{v:'scroll',l:'Scroll'}].forEach(function(m) {
                    html += '<button type="button" class="' + (carouselModeShared === m.v ? 'active' : '') + '" data-value="' + m.v + '" style="height:26px;font-size:11px">' + m.l + '</button>';
                });
                html += '<input type="hidden" name="carousel_mode" value="' + carouselModeShared + '">';
                html += '</div></div>';
            }

            if (elementsData) {
                var elements = elementsData.current || [];
                var allElements = elementsData.all || [
                    {k:'image',l:'Image'},{k:'title',l:'Title'},{k:'price',l:'Price'},{k:'add_to_cart',l:'Button'}
                ]; 
                html += '<div class="impulse-card-elements-grid" style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin-top:6px">';
                allElements.forEach(function(el) {
                    var checked = elements.includes(el.k) ? ' checked' : '';
                    html += '<label class="impulse-card-element-toggle" style="display:flex;align-items:center;gap:6px;font-size:11px;padding:4px 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:4px;cursor:pointer;color:'+ImpC.text+'">';
                    html += '<input type="checkbox" class="impulse-card-element-cb" data-element="' + el.k + '"' + checked + ' style="margin:0">';
                    html += el.l + '</label>';
                });
                html += '</div>';
                html += '<input type="hidden" name="card_design_elements" value=\'' + JSON.stringify(elements) + '\'>';
            }

            var txtStyle = 'width:120px;height:26px;padding:0 8px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;background:'+ImpC.panel+';color:'+ImpC.text+';box-sizing:border-box';
            var showSaleBadge = (d.elements && d.elements.includes && d.elements.includes('sale_badge'));
            if (typeof showSaleBadge === 'undefined') showSaleBadge = true;
            var showFeatBadge = (d.elements && d.elements.includes && d.elements.includes('featured_badge'));
            if (typeof showFeatBadge === 'undefined') showFeatBadge = true;

            html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px">';
            html += '<span style="font-size:11px;color:#888">Button text</span>';
            html += '<input type="text" name="card_design_add_to_cart_button_text" value="' + (d.add_to_cart.button_text || 'Add to Cart') + '" style="' + txtStyle + '">';
            html += '</div>';

            html += '<div style="display:flex;align-items:center;justify-content:space-between;margin-top:6px">';
            html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.text+';cursor:pointer;white-space:nowrap">';
            html += '<input type="checkbox" name="show_sale_badge" id="ppc-sale-badge-cb"' + (showSaleBadge ? ' checked' : '') + ' style="margin:0">';
            html += 'Sale badge</label>';
            html += '<input type="text" name="card_design_sale_badge_text" id="ppc-sale-badge-txt" value="' + (d.sale_badge.text || 'Sale') + '" style="' + txtStyle + ';' + (!showSaleBadge ? 'display:none;' : '') + '">';
            html += '</div>';

            html += '<div style="display:flex;align-items:center;justify-content:space-between;margin-top:6px">';
            html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:'+ImpC.text+';cursor:pointer;white-space:nowrap">';
            html += '<input type="checkbox" name="show_featured_badge" id="ppc-feat-badge-cb"' + (showFeatBadge ? ' checked' : '') + ' style="margin:0">';
            html += 'Featured badge</label>';
            html += '<input type="text" name="card_design_featured_badge_text" id="ppc-feat-badge-txt" value="' + (d.sale_badge.featured_text || 'Featured') + '" style="' + txtStyle + ';' + (!showFeatBadge ? 'display:none;' : '') + '">';
            html += '</div>';

            html += '<script>(function(){';
            html += 'var scb=document.getElementById("ppc-sale-badge-cb");';
            html += 'var stx=document.getElementById("ppc-sale-badge-txt");';
            html += 'if(scb&&stx)scb.addEventListener("change",function(){stx.style.display=scb.checked?"":"none";if(typeof autoSaveAndRefresh==="function")autoSaveAndRefresh();});';
            html += 'var fcb=document.getElementById("ppc-feat-badge-cb");';
            html += 'var ftx=document.getElementById("ppc-feat-badge-txt");';
            html += 'if(fcb&&ftx)fcb.addEventListener("change",function(){ftx.style.display=fcb.checked?"":"none";if(typeof autoSaveAndRefresh==="function")autoSaveAndRefresh();});';
            html += '})()<\/script>';

            var flipEffect = settings.flip_card_effect || '';
            var dm0 = settings.display_mode || 'grid';
            
            var btnS = 'flex:1;height:26px;padding:0;font-size:10px;box-sizing:border-box';
            html += '<div class="impulse-btn-group-rows" style="margin-top:6px">';
            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="flip_card_effect" data-toggleable="1" style="display:flex;width:100%;gap:5px">';
            html += '<button type="button" data-value="flip-h" class="' + (flipEffect==='flip-h'?'active':'') + '" style="' + btnS + '">H-Flip</button>';
            html += '<button type="button" data-value="flip-v" class="' + (flipEffect==='flip-v'?'active':'') + '" style="' + btnS + '">V-Flip</button>';
            html += '<button type="button" data-value="zoom" class="' + (flipEffect==='zoom'?'active':'') + '" style="' + btnS + '">Zoom</button>';
            html += '<input type="hidden" name="flip_card_effect" value="' + flipEffect + '">';
            html += '</div>';
            html += '<div class="impulse-btn-group impulse-btn-group-fullwidth" data-name="flip_card_effect" data-toggleable="1" style="display:flex;width:100%;gap:5px;margin-top:5px">';
            html += '<button type="button" data-value="push" class="' + (flipEffect==='push'?'active':'') + '" style="' + btnS + '">Push</button>';
            html += '<button type="button" data-value="swing" class="' + (flipEffect==='swing'?'active':'') + '" style="' + btnS + '">Swing</button>';
            html += '<button type="button" data-value="fade" class="' + (flipEffect==='fade'?'active':'') + '" style="' + btnS + '">Fade</button>';
            html += '</div>';
            html += '</div>';

            if (showContainerWidth) {

                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:6px">';
                html += '<div><div style="font-size:11px;color:#888;margin-bottom:4px">Border</div>' + settingColorSwatchOnly('card_design_card_border_color', d.card.border_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Price</div>' + settingColorSwatchOnly('card_design_price_color', d.price.color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Background</div>' + settingColorSwatchOnly('card_design_card_background', d.card.background) + '</div>';
                html += '</div>';

                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:6px">';
                html += '<div><div style="font-size:11px;color:#888;margin-bottom:4px">Text</div>' + settingColorSwatchOnly('card_design_title_color', d.title.color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Button</div>' + settingColorSwatchOnly('card_design_add_to_cart_bg_color', d.add_to_cart.bg_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Btn Text</div>' + settingColorSwatchOnly('card_design_add_to_cart_text_color', d.add_to_cart.text_color) + '</div>';
                html += '</div>';

                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:6px">';
                html += '<div><div style="font-size:11px;color:#888;margin-bottom:4px">Sale Price</div>' + settingColorSwatchOnly('card_design_price_sale_color', d.price.sale_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Badge Text</div>' + settingColorSwatchOnly('card_design_sale_badge_text_color', d.sale_badge.text_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Sale Badge</div>' + settingColorSwatchOnly('card_design_sale_badge_bg_color', d.sale_badge.bg_color) + '</div>';
                html += '</div>';

                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:6px">';
                html += '<div></div><div></div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Container</div>' + settingColorSwatchOnly('container_bg', settings.container_bg || '') + '</div>';
                html += '</div>';
            } else {
                
                html += '<div class="impulse-ppc-collapsible" id="ppc-colors-section" style="margin-top:8px">';
                html += '<div class="impulse-ppc-collapsible-hdr" style="display:flex;justify-content:space-between;align-items:center;cursor:pointer;padding:4px 0">';
                html += '<span style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:0.5px">Colors</span>';
                html += '<svg class="impulse-ppc-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="'+ImpC.dim+'" stroke-width="2" style="transform:rotate(-90deg);transition:transform 0.2s"><path d="M6 9l6 6 6-6"/></svg>';
                html += '</div>';
                html += '<div class="impulse-ppc-collapsible-body" style="display:none;padding-top:4px">';
                
                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:2px">';
                html += '<div><div style="font-size:11px;color:#888;margin-bottom:4px">Background</div>' + settingColorSwatchOnly('card_design_card_background', d.card.background) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Border</div>' + settingColorSwatchOnly('card_design_card_border_color', d.card.border_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Text</div>' + settingColorSwatchOnly('card_design_title_color', d.title.color) + '</div>';
                html += '</div>';
                
                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:6px">';
                html += '<div><div style="font-size:11px;color:#888;margin-bottom:4px">Button</div>' + settingColorSwatchOnly('card_design_add_to_cart_bg_color', d.add_to_cart.bg_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Btn Text</div>' + settingColorSwatchOnly('card_design_add_to_cart_text_color', d.add_to_cart.text_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Sale Price</div>' + settingColorSwatchOnly('card_design_price_sale_color', d.price.sale_color) + '</div>';
                html += '</div>';
                
                html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-top:6px">';
                html += '<div><div style="font-size:11px;color:#888;margin-bottom:4px">Featured</div>' + settingColorSwatchOnly('card_design_featured_badge_bg_color', d.sale_badge.featured_bg_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:center"><div style="font-size:11px;color:#888;margin-bottom:4px">Badge Text</div>' + settingColorSwatchOnly('card_design_sale_badge_text_color', d.sale_badge.text_color) + '</div>';
                html += '<div style="display:flex;flex-direction:column;align-items:flex-end"><div style="font-size:11px;color:#888;margin-bottom:4px">Sale Badge</div>' + settingColorSwatchOnly('card_design_sale_badge_bg_color', d.sale_badge.bg_color) + '</div>';
                html += '</div>';
                html += '</div>'; 
                html += '</div>'; 
            }

            

            
            if (isGrid) {
                
                html += '<div class="impulse-padding-grid" style="margin-top:6px">';
                html += settingSlider('gap', 'Gap', gapValue, 0, 40, 'px', false, true);
                var mwMin = colCount * 250; 
                
                if (device === 'desktop') {
                html += settingSlider('section_max_width', 'Max Width', maxWidthValue, mwMin, 1600, 'px');
                } else {
                html += '<div></div>'; 
                }
                html += '</div>';

                html += '<div class="impulse-padding-grid impulse-products-count-wrapper" style="margin-top:6px;' + (!sourceIsQuery ? 'display:none' : '') + '">';
                html += settingSlider('count', 'Products to show', settings.count || 8, 1, 24, '');
                html += '<div></div>';
                html += '</div>';
            } else if (showContainerWidth) {
                
                html += '<div class="impulse-padding-grid" style="margin-top:6px">';
                html += settingSlider('container_width', 'Container', settings.container_width || 300, 150, 500, 'px');
                html += settingSlider('card_design_card_border_radius', 'Radius', d.card.border_radius, 0, 24, 'px');
                html += '</div>';
            } else {
                
                var carouselMode = settings.carousel_mode || 'snap';
                if (carouselMode === 'slide') carouselMode = 'snap';
                var dm2 = settings.display_mode || 'grid';
                var isCarouselMode = (dm2 === 'carousel');
                var isScrollMode   = isCarouselMode && (carouselMode === 'scroll');
                
                var visCount = device === 'mobile' ? (parseInt(settings.columns_mobile) || 2)
                             : device === 'tablet' ? (parseInt(settings.columns_tablet) || 2)
                             : (parseInt(settings.carousel_cards) || parseInt(settings.columns) || 4);

                function sliderRow(id, name, label, val, min, max, unit, hidden) {
                    var h = settingSlider(name, label, val, min, max, unit);
                    return h.replace('<div class=\"impulse-setting-row\"',
                        '<div class=\"impulse-setting-row\"' +
                        (id ? ' id=\"' + id + '\"' : '') +
                        (hidden ? ' style=\"display:none\"' : ''));
                }

                html += '<div id=\"ppc-carousel-section\">';

                var carTransDefault = settings.transition_speed || 800; 
                var carCardW = Math.max(150, parseInt(settings.card_carousel_width) || 250);
                html += '<div class=\"impulse-padding-grid\" style=\"margin-top:6px\">';
                html += settingSlider('gap', 'Gap', gapValue, 0, 40, 'px', false, true);
                html += settingSlider('transition_speed', 'Transition', carTransDefault, 100, 1200, 'ms');
                
                html += sliderRow('ppc-cardwidth-row', 'card_carousel_width', 'Card Width', carCardW, 150, 500, 'px', !isScrollMode);
                html += settingSlider('card_design_card_border_radius', 'Radius', d.card.border_radius, 0, 24, 'px');
                html += sliderRow('', 'count', 'Products', settings.count || 8, 1, 24, '', false);
                html += sliderRow('', 'autoplay_speed', 'Interval', settings.autoplay_speed || 5, 2, 15, 's', false);
                html += sliderRow('ppc-speed-row', 'scroll_speed', 'Speed', settings.scroll_speed || 5, 1, 10, '', !isScrollMode);
                html += settingSlider('card_design_add_to_cart_border_radius', 'Btn Radius', d.add_to_cart.border_radius, 0, 24, 'px');
                html += '</div>';
                html += '</div>'; 

                html += '<script>(function(){' +
                    'var cmEl=document.querySelector(\"[data-name=carousel_mode]\");' +
                    'if(cmEl){cmEl.addEventListener(\"click\",function(e){' +
                        'var btn=e.target.closest(\"button[data-value]\");if(!btn)return;' +
                        'var v=btn.dataset.value;var isScroll=(v===\"scroll\");' +
                        'var mr=document.getElementById(\"ppc-maxcards-row\");' +
                        'var mwr=document.getElementById(\"ppc-cardwidth-row\");' +
                        'var spr=document.getElementById(\"ppc-speed-row\");' +
                        'if(mr)mr.style.display=isScroll?\"none\":\"\";' +
                        'if(mwr)mwr.style.display=isScroll?\"\":\"none\";' +
                        'if(spr)spr.style.display=isScroll?\"\":\"none\";' +
                    '});}' +
                '})();<\/script>';
            }

            if (!isCarousel) {
            html += '<div class="impulse-ppc-collapsible" style="margin-top:4px">';
            html += '<div class="impulse-ppc-collapsible-hdr" style="display:flex;justify-content:space-between;align-items:center;cursor:pointer;padding:4px 0;border-top:1px solid '+ImpC.border+'">';
            html += '<span style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:0.5px">Shape</span>';
            html += '<svg class="impulse-ppc-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="'+ImpC.dim+'" stroke-width="2" style="transform:rotate(-90deg);transition:transform 0.2s"><path d="M6 9l6 6 6-6"/></svg>';
            html += '</div>';
            html += '<div class="impulse-ppc-collapsible-body" style="display:none;padding-top:4px">';
            html += '<div class="impulse-padding-grid">';
            html += settingSlider('card_design_card_border_radius', 'Card Radius', d.card.border_radius, 0, 24, 'px');
            html += settingSlider('card_design_add_to_cart_border_radius', 'Btn Radius', d.add_to_cart.border_radius, 0, 24, 'px');
            html += '</div>';
            html += '</div>'; 
            html += '</div>'; 
            }

            

            if (!elementsData) {
                html += '<input type="hidden" name="card_design_elements" value=\'' + JSON.stringify(d.elements) + '\'>';
            }

            if (showModalTab) {
                var md = $.extend(true, {}, {
                    overlay_opacity: 60,
                    border_radius: 12,
                    max_width: 900,
                    shadow: 'medium',
                    gallery_bg: ''+ImpC.light+'',
                    details_bg: '#ffffff',
                    details_padding: 32,
                    title_size: 24, title_weight: '600', title_color: ''+ImpC.surface2+'',
                    price_size: 28, price_color: ''+ImpC.surface2+'', price_del_color: '#999999',
                    desc_size: 14, desc_color: '#666666',
                    btn_bg: ''+ImpC.surface2+'', btn_text: '#ffffff', btn_radius: 6,
                    show_desc: true, show_desc_type: 'short', show_sku: true,
                    show_price: true, show_qty: true
                }, settings.modal_design || {});

                var enableModal = settings.enable_modal === true || settings.enable_modal === '1' || settings.enable_modal === undefined;
                var showDesc  = !!getResponsiveValue(md, 'show_desc',  true);
                var showPrice = !!getResponsiveValue(md, 'show_price', true);
                var showQty   = !!getResponsiveValue(md, 'show_qty',   true);
                var descType  = getResponsiveValue(md, 'show_desc_type', 'short') || 'short';
                var showLongDesc = showDesc && descType === 'long';

                html += '<div id="ppc-modal-section" style="margin-top:12px">';
                
                html += '<input type="hidden" name="enable_modal" id="ppc-modal-val" value="' + (enableModal ? '1' : '') + '">';
                html += '<button type="button" id="ppc-modal-toggle-btn" style="display:block;width:100%;height:26px;font-size:11px;font-weight:600;letter-spacing:0.5px;border-radius:3px;cursor:pointer;border:none;background:' + (enableModal ? ''+ImpC.white+'' : ''+ImpC.panel+'') + ';color:' + (enableModal ? ''+ImpC.surface2+'' : ''+ImpC.dim+'') + ';text-transform:uppercase">PRODUCT CARD ' + (enableModal ? 'ON' : 'OFF') + '</button>';

                html += '<div id="ppc-modal-body" style="display:' + (enableModal ? 'block' : 'none') + ';padding-top:4px">';

                html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:6px">';
                html += '<div data-responsive="true"><div style="font-size:11px;color:'+ImpC.muted+';margin-bottom:4px">Price</div><input type="checkbox" name="modal_design_show_price"' + (showPrice ? ' checked' : '') + ' style="margin:0;accent-color:#666"></div>';
                html += '<div style="text-align:right" data-responsive="true"><div style="font-size:11px;color:'+ImpC.muted+';margin-bottom:4px">Quantity</div><input type="checkbox" name="modal_design_show_qty"' + (showQty ? ' checked' : '') + ' style="margin:0;accent-color:#666"></div>';
                html += '</div>';
                html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:8px">';
                html += '<div data-responsive="true"><div style="font-size:11px;color:'+ImpC.muted+';margin-bottom:4px">Short Description</div><input type="checkbox" name="modal_design_show_desc" id="md_show_short_desc"' + (showDesc && descType !== 'long' ? ' checked' : '') + ' style="margin:0;accent-color:#666"></div>';
                html += '<div style="text-align:right" data-responsive="true"><div style="font-size:11px;color:'+ImpC.muted+';margin-bottom:4px">Long Description</div><input type="checkbox" name="modal_design_show_long_desc"' + (showLongDesc ? ' checked' : '') + ' style="margin:0;accent-color:#666"></div>';
                html += '</div>';

                html += '<div class="impulse-padding-grid">';
                html += settingSlider('modal_design_max_width', 'Modal Width', getResponsiveValue(md, 'max_width', 900), 480, 1400, 'px', false, true, 900);
                html += settingSlider('modal_design_height', 'Modal Height', getResponsiveValue(md, 'height', 90), 40, 98, 'vh', false, true, 90);
                html += settingSlider('modal_design_border_radius', 'Border Radius', getResponsiveValue(md, 'border_radius', 12), 0, 32, 'px', false, true, 12);
                html += settingSlider('modal_design_overlay_opacity', 'Overlay', md.overlay_opacity, 0, 90, '%', false, false, 60);
                html += settingSlider('modal_design_details_padding', 'Padding', getResponsiveValue(md, 'details_padding', 32), 12, 56, 'px', false, true, 32);
                html += settingSlider('modal_design_desc_size', 'Description Size', md.desc_size, 11, 20, 'px', false, false, 14);
                html += '</div>';

                html += buildAddonsSection(settings);
                html += '</div>'; 
                html += '</div>'; 

            }

            return html;
        }

        function buildBadgeItem(badge, idx) {
            var icon = badge.icon || 'shield';
            var svg = badge.svg || '';
            var text = badge.text || '';
            var color = badge.color || '#666666';
            
            var html = '<div class="impulse-trust-badge-item" data-index="' + idx + '">';

            html += '<div class="impulse-badge-header">';
            html += '<div class="impulse-badge-preview" style="color:' + color + '">';
            if (svg) {
                html += '<img src="' + escapeHtml(svg) + '" style="width:20px;height:20px;object-fit:contain">';
            } else {
                html += lucideSvg(icon, 16);
            }
            html += '</div>';
            html += '<span class="impulse-badge-label">' + escapeHtml(text || 'Badge ' + (idx + 1)) + '</span>';
            html += '<button type="button" class="impulse-badge-remove" title="Remove"><svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
            html += '<svg class="impulse-badge-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>';
            html += '</div>';

            html += '<div class="impulse-badge-content">';

            html += '<div class="impulse-setting-row" style="display:flex;gap:8px">';
            html += '<button type="button" class="instinctor-btn instinctor-btn-sm impulse-badge-select-icon" style="flex:1">Select Icon</button>';
            
            html += '</div>';

            html += '<div class="impulse-setting-row"><label>Label</label>';
            html += '<input type="text" class="impulse-badge-text" value="' + escapeHtml(text) + '" placeholder="Badge label">';
            html += '</div>';

            html += '<div class="impulse-setting-row"><label>Color</label>';
            html += '<div class="impulse-color-input">';
            html += '<input type="color" class="impulse-badge-color-picker" value="' + color + '">';
            html += '<input type="text" class="impulse-badge-color-hex" value="' + color + '" placeholder="#666666">';
            html += '</div></div>';

            html += '<input type="hidden" class="impulse-badge-icon" value="' + escapeHtml(icon) + '">';
            html += '<input type="hidden" class="impulse-badge-svg" value="' + escapeHtml(svg) + '">';
            
            html += '</div>'; 
            html += '</div>'; 
            return html;
        }

        function buildFormFieldRow(field, idx) {
            var type = field.type || 'text';
            var label = field.label || 'New Field';
            var required = field.required || false;

            var device = window.impulseDevice || 'desktop';
            var width;
            if (device === 'mobile') {
                width = field.width_mobile !== undefined ? field.width_mobile : 100; 
            } else if (device === 'tablet') {
                width = field.width_tablet !== undefined ? field.width_tablet : (field.width || 100);
            } else {
                width = field.width || 100;
            }

            var showWidth = type !== 'textarea' && type !== 'checkbox';
            var isHalf = width === 50 || width === '50';
            
            var html = '<div class="impulse-form-field-item" data-index="' + idx + '">';
            html += '<span class="impulse-field-drag"><span class="dashicons dashicons-menu"></span></span>';
            html += '<span class="impulse-field-label">' + escapeHtml(label) + (required ? ' <span class="impulse-req">*</span>' : '') + '</span>';

            html += '<div class="impulse-field-controls">';
            html += '<button type="button" class="impulse-field-delete" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Delete"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
            if (showWidth) {
                html += '<button type="button" class="impulse-width-toggle' + (isHalf ? '' : ' active') + '">' + (isHalf ? 'Half' : 'Full') + '</button>';
            }
            html += '</div>';

            html += '<input type="hidden" class="impulse-field-data" value=\'' + JSON.stringify(field).replace(/'/g, '&#39;') + '\'>';
            html += '</div>';
            return html;
        }

        
        function getActiveScreenId() {
            try {
                var iframeDoc = document.getElementById('impulse-iframe').contentDocument;
                var active = iframeDoc.querySelector('.impulse-content-wrapper > .impulse-el[data-type="section"].impulse-screen-active');
                if (active) return parseInt(active.dataset.id);
                var first = iframeDoc.querySelector('.impulse-content-wrapper > .impulse-el[data-type="section"]');
                if (first) return parseInt(first.dataset.id);
            } catch(e) {}
            return null;
        }
        function getActiveScreenIndex() {
            try {
                var iframeDoc = document.getElementById('impulse-iframe').contentDocument;
                var all = Array.from(iframeDoc.querySelectorAll('.impulse-content-wrapper > .impulse-el[data-type="section"]'));
                var active = iframeDoc.querySelector('.impulse-content-wrapper > .impulse-el[data-type="section"].impulse-screen-active');
                if (active && all.length) return all.indexOf(active);
            } catch(e) {}
            return 0;
        }

        var _envPerScreenKeys = [
            'screen_cloud_effect',
            'screen_3d_color1','screen_3d_color2','screen_3d_color3','screen_3d_color4',
            'screen_3d_speed','screen_3d_intensity','screen_mouse_sens_level',
            'screen_lava_color1','screen_lava_color2','screen_wave_color1','screen_wave_color2',
            'screen_depth_image','screen_depth_map','screen_depth_enabled','screen_depth_strength','screen_depth_free'
        ];
        var _saveScreenEnvTimer = null;
        function _saveScreenEnvSettings() {
            clearTimeout(_saveScreenEnvTimer);
            _saveScreenEnvTimer = setTimeout(function() {
                var screenId = getActiveScreenId();
                if (!screenId) return;
                
                var screenIdx = getActiveScreenIndex();
                if (screenIdx === 0 && window._basePageEnv) {
                    _envPerScreenKeys.forEach(function(k) {
                        var $inp = $('input[name="' + k + '"]');
                        if ($inp.length) window._basePageEnv[k] = $inp.val();
                    });
                }
                var envSettings = {};

                

                
                var _curEnvEff = ($('input[name="screen_cloud_effect"]').val() || '').toLowerCase();
                var _saveKeys = _envPerScreenKeys.slice();
                if (_curEnvEff && _curEnvEff !== 'none' && _curEnvEff !== 'depth_image') {
                    ['color1','color2','color3','color4','speed','intensity','preset','bg_color','count','density','variation','halo'].forEach(function(suf) {
                        var k = 'screen_' + _curEnvEff + '_' + suf;
                        if (_saveKeys.indexOf(k) === -1) _saveKeys.push(k);
                    });
                }
                _saveKeys.forEach(function(k) {
                    var $input = $('input[name="' + k + '"]');
                    if ($input.length) envSettings[k] = $input.val();
                });
                if (!Object.keys(envSettings).length) return;
                
                try {
                    var _ifrDoc = document.getElementById('impulse-iframe').contentDocument;
                    var _el = _ifrDoc.querySelector('.impulse-el[data-id="' + screenId + '"]');
                    if (_el) {
                        if (envSettings.screen_3d_color1)       _el.dataset.envC1  = envSettings.screen_3d_color1;
                        if (envSettings.screen_3d_color2)       _el.dataset.envC2  = envSettings.screen_3d_color2;
                        if (envSettings.screen_3d_color3)       _el.dataset.envC3  = envSettings.screen_3d_color3;
                        if (envSettings.screen_3d_color4)       _el.dataset.envC4  = envSettings.screen_3d_color4;
                        if (envSettings.screen_3d_speed !== undefined)         _el.dataset.envSpd = envSettings.screen_3d_speed;
                        if (envSettings.screen_3d_intensity !== undefined)     _el.dataset.envInt = envSettings.screen_3d_intensity;
                        if (envSettings.screen_mouse_sens_level !== undefined) _el.dataset.envSns = envSettings.screen_mouse_sens_level;
                    }
                } catch(e) {}
                $.ajax({
                    url: Impulse.api + 'elements/' + screenId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: envSettings, page_id: Impulse.pageId })
                });
            }, 600);
        }

        
        
        function _loadScreenEnvIntoBar(screenEl) {

            

            
            var _curEff = ($('input[name="screen_cloud_effect"]').val() || (Impulse.pageSettings || {}).screen_cloud_effect || '').toLowerCase();
            function _barVal(slot) {
                if (_curEff) {
                    var v = $('input[name="screen_' + _curEff + '_color' + slot + '"]').val();
                    if (v) return v;
                }
                return $('input[name="screen_3d_color' + slot + '"]').val()
                    || (window._basePageEnv || {})['screen_3d_color' + slot] || '';
            }
            function _barNum(key, legacyKey, fallback) {
                if (_curEff) {
                    var v = $('input[name="screen_' + _curEff + '_' + key + '"]').val();
                    if (v != null && v !== '') return v;
                }
                var lv = $('input[name="' + legacyKey + '"]').val();
                if (lv != null && lv !== '') return lv;
                return (window._basePageEnv || {})[legacyKey] || fallback;
            }

            
            
            var fromSettings = {
                screen_cloud_effect:    _curEff,
                screen_3d_color1:       _barVal(1) || '#000000',
                screen_3d_color2:       _barVal(2) || '#333333',
                screen_3d_color3:       _barVal(3) || '#666666',
                screen_3d_color4:       _barVal(4) || '#cccccc',
                screen_3d_speed:        _barNum('speed',     'screen_3d_speed',     10),
                screen_3d_intensity:    _barNum('intensity', 'screen_3d_intensity', 5),
                screen_mouse_sens_level:$('input[name="screen_mouse_sens_level"]').val() || (window._basePageEnv || {}).screen_mouse_sens_level || 5
            };

            
            
            var screenSettings = Object.assign({}, Impulse.pageSettings || {});
            _envPerScreenKeys.forEach(function(k) {
                if ((window._basePageEnv || {})[k] !== undefined) screenSettings[k] = window._basePageEnv[k];
            });
            screenSettings.screen_cloud_effect = _curEff || screenSettings.screen_cloud_effect;
            if (screenEl) {
                var ds = screenEl.dataset;
                if (ds.envC1)                                screenSettings.screen_3d_color1       = ds.envC1;
                if (ds.envC2)                                screenSettings.screen_3d_color2       = ds.envC2;
                if (ds.envC3)                                screenSettings.screen_3d_color3       = ds.envC3;
                if (ds.envC4)                                screenSettings.screen_3d_color4       = ds.envC4;
                if (ds.envSpd !== undefined && ds.envSpd !== '') screenSettings.screen_3d_speed       = ds.envSpd;
                if (ds.envInt !== undefined && ds.envInt !== '') screenSettings.screen_3d_intensity   = ds.envInt;
                if (ds.envSns !== undefined && ds.envSns !== '') screenSettings.screen_mouse_sens_level = ds.envSns;
            }
            
            var dur = parseInt((Impulse.pageSettings || {}).screen_duration) || 700;
            _lerpEnvToSettings(fromSettings, screenSettings, dur);
        }

        var _envLerpRaf = null;
        function _lerpEnvToSettings(fromSettings, targetSettings, dur) {
            if (_envLerpRaf) { cancelAnimationFrame(_envLerpRaf); _envLerpRaf = null; }

            function hexToRgb(hex) {
                hex = (hex || '#000000').replace(/[^#0-9a-fA-F]/g, '');
                if (hex.length < 7) hex = '#000000';
                return [parseInt(hex.slice(1,3),16)/255, parseInt(hex.slice(3,5),16)/255, parseInt(hex.slice(5,7),16)/255];
            }
            function rgbToHex(r,g,b) {
                return '#' + [r,g,b].map(function(v){ return Math.round(v*255).toString(16).padStart(2,'0'); }).join('');
            }
            function lerpN(a,b,t){ return a + (b-a)*t; }
            function lerpRgb(a,b,t){ return [lerpN(a[0],b[0],t),lerpN(a[1],b[1],t),lerpN(a[2],b[2],t)]; }

            

            
            function pickColor(src, effect, slot, fallback) {
                if (effect) {
                    var k = 'screen_' + effect + '_color' + slot;
                    if (src && src[k]) return src[k];
                }
                var lk = 'screen_3d_color' + slot;
                return (src && src[lk]) || fallback;
            }
            function pickNum(src, effect, key, legacyKey, fallback) {
                if (effect) {
                    var k = 'screen_' + effect + '_' + key;
                    if (src && src[k] != null && src[k] !== '') return src[k];
                }
                if (src && src[legacyKey] != null && src[legacyKey] !== '') return src[legacyKey];
                return fallback;
            }

            var fEff = (fromSettings && fromSettings.screen_cloud_effect) || '';
            var tEff = (targetSettings && targetSettings.screen_cloud_effect) || fEff;

            var c1f = hexToRgb(pickColor(fromSettings, fEff, 1, '#000000'));
            var c2f = hexToRgb(pickColor(fromSettings, fEff, 2, '#333333'));
            var c3f = hexToRgb(pickColor(fromSettings, fEff, 3, '#666666'));
            var c4f = hexToRgb(pickColor(fromSettings, fEff, 4, '#cccccc'));
            var sf  = parseInt(pickNum(fromSettings, fEff, 'speed',     'screen_3d_speed',     10));
            var inf = parseInt(pickNum(fromSettings, fEff, 'intensity', 'screen_3d_intensity', 5));
            var snf = parseFloat(fromSettings.screen_mouse_sens_level || 5);

            var c1t = hexToRgb(pickColor(targetSettings, tEff, 1, '#000000'));
            var c2t = hexToRgb(pickColor(targetSettings, tEff, 2, '#333333'));
            var c3t = hexToRgb(pickColor(targetSettings, tEff, 3, '#666666'));
            var c4t = hexToRgb(pickColor(targetSettings, tEff, 4, '#cccccc'));
            var st  = parseInt(pickNum(targetSettings, tEff, 'speed',     'screen_3d_speed',     10));
            var int = parseInt(pickNum(targetSettings, tEff, 'intensity', 'screen_3d_intensity', 5));
            var snt = parseFloat(targetSettings.screen_mouse_sens_level || 5);

            
            var _needsColor3 = (tEff === 'nebula');

            var _ifrm = document.getElementById('impulse-iframe');
            var start = null;
            function step(ts) {
                var _cw = _ifrm && _ifrm.contentWindow;
                var _fx  = _cw && _cw._impulseFX;
                var _3d  = _cw && _cw._impulse3D;
                if (!_fx && !_3d) { _envLerpRaf = null; return; }
                if (!start) start = ts;
                var t = Math.min((ts - start) / dur, 1);
                var e = t < 0.5 ? 2*t*t : -1+(4-2*t)*t;
                var c1 = lerpRgb(c1f, c1t, e);
                var c2 = lerpRgb(c2f, c2t, e);
                var c3 = lerpRgb(c3f, c3t, e);
                var c4 = lerpRgb(c4f, c4t, e);
                var spd = lerpN(sf, st, e) / 10;
                var intensity = lerpN(inf, int, e) / 10;
                var c1hex = rgbToHex(c1[0], c1[1], c1[2]);
                var c2hex = rgbToHex(c2[0], c2[1], c2[2]);
                var c3hex = rgbToHex(c3[0], c3[1], c3[2]);
                var c4hex = rgbToHex(c4[0], c4[1], c4[2]);
                if (_fx && _fx.update) {
                    var _upd = { color1: c1hex, color2: c2hex, speed: spd, intensity: intensity, mouse: lerpN(snf, snt, e) / 10 };

                    
                    
                    if (_needsColor3) _upd.color3 = c3hex;
                    _fx.update(_upd);
                }
                if (_3d) {
                    if (_3d.updateColors) _3d.updateColors([c1hex, c2hex, c3hex, c4hex]);
                    if (_3d.updateSpeed)  _3d.updateSpeed(spd);
                    if (_3d.updateIntensity) _3d.updateIntensity(intensity);
                }
                if (t < 1) _envLerpRaf = requestAnimationFrame(step);
                else _envLerpRaf = null;
            }
            _envLerpRaf = requestAnimationFrame(step);
        }

        function addElement(type, parentId, position, template, cellGridData, slideIndex) {
            var debug = window.impulseDebug || false;
            if (debug) console.log('[addElement] called:', { type: type, parentId: parentId, position: position, template: template, cellGridData: cellGridData });

            
            var _rootOverlay = ['section', 'header', 'footer', 'modal'];
            if ((Impulse.pageSettings && ((Impulse.pageSettings.body_scroll || 'snap') !== 'classic')) && _rootOverlay.indexOf(type) === -1 && (!parentId || parentId === 0)) {
                var activeScreen = getActiveScreenId();
                if (activeScreen) {
                    parentId = activeScreen;
                    if (debug) console.log('[addElement] Screen guard: redirected to active screen', activeScreen);
                } else {
                    return;
                }
            }

            if (!Impulse.pageId) {
                console.error('Cannot add element: no page is open');
                return;
            }

            var currentId = $('.impulse-panel-right').data('element-id');
            if (currentId && $('#impulse-settings-body').text().indexOf('Loading') === -1 && 
                !isPageSettingsMode()) {

                if (typeof cellGridSaveTimer !== 'undefined' && cellGridSaveTimer) {
                    clearTimeout(cellGridSaveTimer);
                    cellGridSaveTimer = null;
                }
                
                try {
                    var settings = collectSettingsFromPanel();
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + currentId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: settings, page_id: Impulse.pageId }),
                        async: false 
                    });
                } catch(e) {
                }
            }

            var sortOrder;
            if (position !== null && position !== undefined && !isNaN(position) && position >= 0) {
                sortOrder = position;
            } else {
                sortOrder = -1;
            }

            var initialSettings = null;
            if (cellGridData && cellGridData.row !== undefined && cellGridData.col !== undefined) {
                initialSettings = {
                    _cell_row: cellGridData.row,
                    _cell_col: cellGridData.col
                };
            }

            
            
            try {
                var _udRaw = localStorage.getItem('impulse_default_' + type);
                if (_udRaw) {
                    var _userDef = JSON.parse(_udRaw);
                    if (_userDef && typeof _userDef === 'object') {
                        initialSettings = Object.assign({}, _userDef, initialSettings || {});
                    }
                }
            } catch (e) {}

            
            
            if (type === 'grid') {
                initialSettings = initialSettings || {};
                if (initialSettings.columns === undefined) initialSettings.columns = 2;
                if (initialSettings.rows === undefined)    initialSettings.rows = 1;
            }
            
            if (type === 'price_list') {
                initialSettings = initialSettings || {};
                initialSettings.pl_items = JSON.stringify([
                    {title:'Item One',desc:'',price:'$50',icon:'circle'},
                    {title:'Item Two',desc:'',price:'$99',icon:'circle'}
                ]);
            }

            if (type === 'chart') {
                initialSettings = initialSettings || {};
                initialSettings.chart_type = 'pie';
                initialSettings.chart_style = 'flat';
                initialSettings.chart_entries = JSON.stringify([
                    { label: 'Category A', value: 30, color: '#1D2327' },
                    { label: 'Category B', value: 20, color: '#4A4E53' },
                    { label: 'Category C', value: 15, color: '#737780' },
                    { label: 'Category D', value: 10, color: '#9DA2A9' }
                ]);
                initialSettings.chart_legend_pos = 'right';
                initialSettings.chart_label_format = 'none';
                initialSettings.chart_animate = 1;
            }

            
            if (type === 'configurator') {
                initialSettings = initialSettings || {};
                if (initialSettings.cfg_name === undefined)  initialSettings.cfg_name = 'Custom Pizza';
                if (initialSettings.cfg_sizes === undefined) initialSettings.cfg_sizes = [
                    { name: 'Small',  price: 11.99 },
                    { name: 'Medium', price: 15.99 },
                    { name: 'Large',  price: 19.99 }
                ];
                if (initialSettings.cfg_size_default === undefined) initialSettings.cfg_size_default = 'Medium';
                if (initialSettings.configurator === undefined)     initialSettings.configurator = [];
            }

            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({
                    element_type: type,
                    parent_id: parentId || null,
                    sort_order: sortOrder,
                    settings: initialSettings
                }),
                success: function(resp) {
                    if (resp.id && resp.id > 0) {
                        saveToHistory('add', {
                            elementId: resp.id,
                            elementType: type,
                            parentId: parentId,
                            sortOrder: resp.sort_order || sortOrder,
                            settings: resp.settings || initialSettings || {}
                        });

                        injectNewElement(resp.id, type, null, resp.sort_order || sortOrder, null, null, cellGridData || null, slideIndex);
                        setTimeout(updateStructureTree, 300);

                    } else {
                        console.error('Insert failed:', resp.error, resp.db_error);
                        window.showToast && window.showToast('Failed to add element: ' + (resp.db_error || resp.error || 'Unknown error'), 'error');
                    }
                },
                error: function(xhr, status, error) {
                    
                    if (xhr.status === 503 && !this._retried) {
                        this._retried = true;
                        var self = this;
                        setTimeout(function() { $.ajax(self); }, 1500);
                        return;
                    }
                    console.error('addElement error:', status, error, xhr.responseText);
                    window.showToast && window.showToast('Failed to add element: ' + error, 'error');
                }
            });
        }

        

        
        
        function injectNewElement(elementId, elementType, onDone, sortOrder, siblingId, siblingPosition, cellGridData, slideIndex) {
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentWindow) {
                openSettings(elementId, elementType);
                if (onDone) onDone(elementId);
                return;
            }

            var _done = false;
            function _handler(e) {
                if (!e.data || e.data.type !== 'impulse-element-fetched') return;
                if (e.data.elementId != elementId) return;
                if (_done) return;
                _done = true;
                window.removeEventListener('message', _handler);

                if (e.data.html) {
                    try {
                        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        var tmp = iframeDoc.createElement('div');
                        tmp.innerHTML = e.data.html;
                        var newEl = tmp.firstElementChild;
                        if (newEl) {
                            var insertParent = null;
                            if (e.data.parentId) {
                                var pEl = iframeDoc.querySelector('.impulse-el[data-id="' + e.data.parentId + '"]');
                                if (pEl) {
                                    var pType = pEl.dataset.type;
                                    if (pType === 'grid') {
                                        
                                        var gridCell = pEl.querySelector('.impulse-grid-cell[data-cell="' + sortOrder + '"]');
                                        insertParent = gridCell || pEl;
                                    } else if (pType === 'rows' && cellGridData && cellGridData.row !== undefined) {
                                        var cgCell = pEl.querySelector('.impulse-rows-cell[data-row="' + cellGridData.row + '"][data-col="' + cellGridData.col + '"]');
                                        insertParent = cgCell || pEl;
                                    } else if (pType === 'columns' && cellGridData && cellGridData.row !== undefined) {
                                        var ffCell = pEl.querySelector('.impulse-layout-cell[data-row="' + cellGridData.row + '"][data-col="' + cellGridData.col + '"]');
                                        insertParent = ffCell || pEl;
                                    } else if (pType === 'modal') {

                                        

                                        
                                        insertParent = pEl.querySelector('.impulse-modal-content')
                                                    || iframeDoc.querySelector('.impulse-modal-scrim[data-modal-owner="' + e.data.parentId + '"] .impulse-modal-content')
                                                    || pEl.querySelector('.impulse-modal-drawer-content')
                                                    || pEl;
                                    } else if (pType === 'slider' || pType === 'carousel') {
                                        
                                        var sliderSlideIdx = 0;
                                        if (slideIndex !== undefined && slideIndex !== null) {
                                            sliderSlideIdx = parseInt(slideIndex) || 0;
                                        } else {
                                            var panelSlideInput = document.querySelector('input[name="current_slide"]');
                                            if (panelSlideInput) sliderSlideIdx = parseInt(panelSlideInput.value) || 0;
                                            var panelElId = $('.impulse-panel-right').data('element-id');
                                            if (String(panelElId) !== String(e.data.parentId)) {
                                                var carouselEl = pEl.querySelector('.impulse-new-slider');
                                                sliderSlideIdx = carouselEl ? (parseInt(carouselEl.dataset.currentSlide) || 0) : 0;
                                            }
                                        }
                                        var slideDz = pEl.querySelector('.impulse-new-slider-dropzone[data-slide="' + sliderSlideIdx + '"]');
                                        insertParent = slideDz || pEl.querySelector('.impulse-new-slider-dropzone') || pEl;
                                    } else {
                                        
                                        insertParent = pEl.querySelector('.impulse-container') || pEl.querySelector('.impulse-section') || pEl;
                                    }
                                }
                            }
                            if (!insertParent) insertParent = iframeDoc.querySelector('.impulse-content-wrapper');
                            if (insertParent) {
                                var inserted = false;
                                
                                if (siblingId && siblingPosition) {
                                    var siblingEl = iframeDoc.querySelector('.impulse-el[data-id="' + siblingId + '"]');
                                    if (siblingEl && siblingEl.parentNode === insertParent) {
                                        if (siblingPosition === 'before') {
                                            insertParent.insertBefore(newEl, siblingEl);
                                        } else {
                                            insertParent.insertBefore(newEl, siblingEl.nextSibling);
                                        }
                                        inserted = true;
                                    }
                                }
                                
                                if (!inserted && sortOrder !== undefined && sortOrder >= 0) {
                                    var siblings = insertParent.querySelectorAll(':scope > .impulse-el');
                                    if (sortOrder < siblings.length) {
                                        insertParent.insertBefore(newEl, siblings[sortOrder]);
                                        inserted = true;
                                    }
                                }
                                if (!inserted) {

                                    
                                    var _trailingDz = insertParent.classList && insertParent.classList.contains('impulse-modal-content')
                                        ? insertParent.querySelector(':scope > .impulse-modal-dropzone')
                                        : null;
                                    if (_trailingDz) insertParent.insertBefore(newEl, _trailingDz);
                                    else insertParent.appendChild(newEl);
                                }

                                if (insertParent.classList && insertParent.classList.contains('impulse-new-slider-dropzone')) {
                                    var _emptyInd = insertParent.querySelector('.impulse-cell-empty-indicator');
                                    if (_emptyInd) _emptyInd.remove();
                                    var _slideEl = insertParent.closest('.impulse-carousel-slide');
                                    if (_slideEl) _slideEl.classList.remove('impulse-carousel-slide-empty');
                                }

                                

                                

                                

                                

                                if (insertParent.classList) {
                                    var _emptyClasses = ['impulse-grid-cell-empty', 'impulse-rows-cell-empty', 'impulse-layout-cell-empty'];
                                    _emptyClasses.forEach(function (cls) {
                                        if (insertParent.classList.contains(cls)) {
                                            insertParent.classList.remove(cls);
                                        }
                                    });

                                    

                                    var _cellInlineBg = insertParent.style.background || '';
                                    var _tintRe = /^rgba?\(\s*128\s*,\s*128\s*,\s*128\s*,\s*0?\.03\s*\)$/i;
                                    if (_tintRe.test(_cellInlineBg.trim())) {
                                        insertParent.style.removeProperty('background');
                                    }

                                    var _empInd2 = insertParent.querySelector('.impulse-cell-empty-indicator');
                                    if (_empInd2) _empInd2.remove();
                                }

                                var scripts = newEl.querySelectorAll('script');
                                for (var si = 0; si < scripts.length; si++) {
                                    var oldScript = scripts[si];
                                    var freshScript = iframeDoc.createElement('script');
                                    if (oldScript.src) freshScript.src = oldScript.src;
                                    else freshScript.textContent = oldScript.textContent;
                                    oldScript.parentNode.replaceChild(freshScript, oldScript);
                                }
                                if (iframe.contentWindow.impulseReinitSortables) {
                                    iframe.contentWindow.impulseReinitSortables();
                                }

                                

                                
                                
                                try {
                                    var _newAnims = [];
                                    if (newEl.classList && newEl.classList.contains('impulse-logo-animator')) {
                                        _newAnims.push(newEl);
                                    }
                                    if (newEl.querySelectorAll) {
                                        var _inner = newEl.querySelectorAll('.impulse-logo-animator');
                                        for (var _i = 0; _i < _inner.length; _i++) _newAnims.push(_inner[_i]);
                                    }
                                    if (_newAnims.length && iframe.contentWindow.runAnimator) {
                                        var _cw = iframe.contentWindow;

                                        _cw.requestAnimationFrame(function() {
                                            _cw.requestAnimationFrame(function() {
                                                setTimeout(function() {
                                                    for (var _ai = 0; _ai < _newAnims.length; _ai++) {
                                                        try { _cw.runAnimator(_newAnims[_ai]); }
                                                        catch(_e) { console.warn('[animator] runAnimator failed', _e); }
                                                    }
                                                }, 60);
                                            });
                                        });
                                    }
                                } catch(_laE) {  }
                                
                                var _emptyPg = iframeDoc.querySelector('.impulse-empty-page');
                                if (_emptyPg) _emptyPg.style.display = 'none';
                                
                                if (!((Impulse.pageSettings && (true)))) {
                                    newEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                }
                            }
                        }
                    } catch(ex) {
                        console.warn('[injectNewElement] inject failed:', ex);
                    }
                }
                setTimeout(function() {
                    openSettings(elementId, elementType);
                    if (onDone) onDone(elementId);
                }, 80);
            }
            window.addEventListener('message', _handler);

            setTimeout(function() {
                if (_done) return;
                _done = true;
                window.removeEventListener('message', _handler);
                openSettings(elementId, elementType);
                if (onDone) onDone(elementId);
            }, 5000);

            iframe.contentWindow.postMessage({
                type:        'impulse-fetch-element',
                elementId:   elementId,
                elementType: elementType,
                pageId:      Impulse.pageId,
                device:      window.impulseDevice || 'desktop'
            }, '*');
        }

        function addElementNearSibling(type, siblingId, position) {

            if (!Impulse.pageId) {
                console.error('Cannot add element: no page is open');
                return;
            }

            
            var currentId = $('.impulse-panel-right').data('element-id');
            if (currentId && $('#impulse-settings-body').text().indexOf('Loading') === -1 && 
                !isPageSettingsMode()) {
                var settings = collectSettingsFromPanel();
                $.ajax({
                    url: Impulse.api + 'elements/' + currentId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: settings, page_id: Impulse.pageId }),
                    async: false
                });
            }

            var _nsInitialSettings = null;
            try {
                var _nsRaw = localStorage.getItem('impulse_default_' + type);
                if (_nsRaw) {
                    var _nsDef = JSON.parse(_nsRaw);
                    if (_nsDef && typeof _nsDef === 'object') _nsInitialSettings = _nsDef;
                }
            } catch (e) {}

            var _nsBody = {
                element_type: type,
                sibling_id: siblingId,
                insert_position: position 
            };
            if (_nsInitialSettings) _nsBody.settings = _nsInitialSettings;
            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify(_nsBody),
                success: function(resp) {
                    if (resp.id && resp.id > 0) {
                        saveToHistory('add', {
                            elementId: resp.id,
                            elementType: type,
                            siblingId: siblingId,
                            position: position,
                            parentId: resp.parent_id || 0,
                            sortOrder: resp.sort_order || 0,
                            settings: resp.settings || initialSettings || {}
                        });
                        
                        pendingSelectElement = null;
                        injectNewElement(resp.id, type, null, resp.sort_order || 0, siblingId, position);
                        setTimeout(updateStructureTree, 300);
                    } else {
                        console.error('Insert failed:', resp.error);
                        window.showToast && window.showToast('Failed to add element', 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('addElementNearSibling error:', error);
                    window.showToast && window.showToast('Failed to add element', 'error');
                }
            });
        }

        

        var _refreshDebounce = {};
        window._refreshDebounce = _refreshDebounce;
        function refreshElement(elementId) {
            
            if (_refreshDebounce[elementId]) clearTimeout(_refreshDebounce[elementId]);
            _refreshDebounce[elementId] = setTimeout(function() {
                delete _refreshDebounce[elementId];
                _doRefreshElement(elementId);
            }, 400);
        }
        function _doRefreshElement(elementId) {
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentWindow) return;
            var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            if (!iframeDoc) return;
            
            var existing = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"]');
            if (!existing) return;

            var _sliderParent = existing.closest('.impulse-el[data-type="carousel"], .impulse-el[data-type="slider"]');
            if (_sliderParent && _sliderParent.dataset.id && _sliderParent.dataset.id != elementId) {
                var _sliderParentId = parseInt(_sliderParent.dataset.id, 10);
                if (_sliderParentId) { refreshElement(_sliderParentId); return; }
            }

            var _done = false;
            function _handler(e) {
                if (!e.data || e.data.type !== 'impulse-element-fetched') return;
                if (e.data.elementId != elementId) return;
                if (_done) return;
                _done = true;
                window.removeEventListener('message', _handler);

                if (!e.data.html) return;
                try {
                    
                    var _liveIframe = document.getElementById('impulse-iframe');
                    var _liveDoc = _liveIframe ? (_liveIframe.contentDocument || _liveIframe.contentWindow.document) : null;
                    if (!_liveDoc) return;
                    var _liveExisting = _liveDoc.querySelector('.impulse-el[data-id="' + elementId + '"]');
                    if (!_liveExisting) return;
                    iframeDoc = _liveDoc;
                    existing = _liveExisting;
                    var tmp = iframeDoc.createElement('div');
                    tmp.innerHTML = e.data.html;
                    var newEl = tmp.firstElementChild;
                    if (!newEl) return;
                    
                    var wasSelected        = existing.classList.contains('selected');
                    var wasScreenActive    = existing.classList.contains('impulse-screen-active');
                    var wasScreenAnimating = existing.classList.contains('impulse-screen-animating');
                    var wasDeviceHidden    = existing.classList.contains('impulse-device-hidden');
                    var wasUrgent          = existing.classList.contains('impulse-cd-urgent');

                    

                    var _selCell = existing.querySelector('.impulse-grid-cell.selected,.impulse-rows-cell.selected,.impulse-layout-cell.selected');
                    var _selCellSig = null;
                    if (_selCell) {
                        _selCellSig = {
                            cls:  _selCell.classList.contains('impulse-grid-cell') ? 'impulse-grid-cell'
                                : _selCell.classList.contains('impulse-rows-cell') ? 'impulse-rows-cell'
                                : 'impulse-layout-cell',
                            cell: _selCell.getAttribute('data-cell'),
                            row:  _selCell.getAttribute('data-row'),
                            col:  _selCell.getAttribute('data-col')
                        };
                    }

                    

                    

                    

                    
                    
                    try {
                        var _oldAnims = existing.querySelectorAll('.impulse-logo-animator');
                        for (var _oa = 0; _oa < _oldAnims.length; _oa++) {
                            var _oldAnim = _oldAnims[_oa];
                            if (_oldAnim._la3dRenderer) {
                                try { _oldAnim._la3dRenderer.forceContextLoss(); } catch (_e) {}
                                try { _oldAnim._la3dRenderer.dispose(); } catch (_e) {}
                                _oldAnim._la3dRenderer = null;
                            }
                            if (_oldAnim._la3dRaf) {
                                try { iframe.contentWindow.cancelAnimationFrame(_oldAnim._la3dRaf); } catch (_e) {}
                                _oldAnim._la3dRaf = null;
                            }
                            if (_oldAnim._laCancel) {
                                try { _oldAnim._laCancel(); } catch (_e) {}
                                _oldAnim._laCancel = null;
                            }
                        }
                    } catch (_glDisposeErr) {}
                    
                    existing.parentNode.replaceChild(newEl, existing);

                    
                    
                    if (wasSelected && !_selCellSig) newEl.classList.add('selected');
                    if (wasScreenActive)    newEl.classList.add('impulse-screen-active');
                    if (wasScreenAnimating) newEl.classList.add('impulse-screen-animating');
                    if (wasDeviceHidden)    newEl.classList.add('impulse-device-hidden');
                    if (wasUrgent)          newEl.classList.add('impulse-cd-urgent');
                    
                    if (_selCellSig) {
                        var _cq = '.' + _selCellSig.cls;
                        if (_selCellSig.cell !== null && _selCellSig.cell !== '') {
                            _cq += '[data-cell="' + _selCellSig.cell + '"]';
                        } else {
                            if (_selCellSig.row !== null) _cq += '[data-row="' + _selCellSig.row + '"]';
                            if (_selCellSig.col !== null) _cq += '[data-col="' + _selCellSig.col + '"]';
                        }
                        var _newCell = newEl.querySelector(_cq);
                        if (_newCell) _newCell.classList.add('selected');
                    }
                    
                    var scripts = newEl.querySelectorAll('script');
                    for (var si = 0; si < scripts.length; si++) {
                        var oldScript = scripts[si];
                        var newScript = iframeDoc.createElement('script');
                        if (oldScript.src) {
                            newScript.src = oldScript.src;
                        } else {
                            newScript.textContent = oldScript.textContent;
                        }
                        oldScript.parentNode.replaceChild(newScript, oldScript);
                    }

                    
                    
                    var oldHeadStyles = iframeDoc.head.querySelectorAll('style[data-el-id="' + elementId + '"]');
                    for (var osi = 0; osi < oldHeadStyles.length; osi++) {
                        oldHeadStyles[osi].remove();
                    }
                    var styles = newEl.querySelectorAll('style');
                    for (var sti = 0; sti < styles.length; sti++) {
                        var elStyle = styles[sti];
                        var headStyle = iframeDoc.createElement('style');
                        headStyle.textContent = elStyle.textContent;
                        headStyle.dataset.elId = elementId;
                        iframeDoc.head.appendChild(headStyle);
                    }

                    
                    if (iframe.contentWindow.impulseReinitSortables) {
                        setTimeout(function() {
                            if (iframe.contentWindow.impulseReinitSortables) {
                                iframe.contentWindow.impulseReinitSortables();
                            }
                        }, 50);
                    }
                    
                    if (iframe.contentWindow.impulseReinitElement) {
                        iframe.contentWindow.impulseReinitElement(elementId);
                    }

                    

                    if (iframe.contentWindow.ImpulseSectionFx && iframe.contentWindow.ImpulseSectionFx.reinit) {
                        iframe.contentWindow.ImpulseSectionFx.reinit();
                    }

                    
                    
                    if (iframe.contentWindow.ImpulseNetwork && iframe.contentWindow.ImpulseNetwork.init) {
                        iframe.contentWindow.ImpulseNetwork.init(newEl);
                    }

                    

                    
                    
                    if (iframe.contentWindow.impulseScreenMode && iframe.contentWindow.impulseScreenMode.refresh) {
                        iframe.contentWindow.impulseScreenMode.refresh();
                    }
                    
                    updateStructureTree();
                } catch(ex) {
                    console.warn('[refreshElement] swap failed:', ex);
                }
            }
            window.addEventListener('message', _handler);
            
            setTimeout(function() {
                if (!_done) { _done = true; window.removeEventListener('message', _handler); }
            }, 5000);

            iframe.contentWindow.postMessage({
                type:        'impulse-fetch-element',
                elementId:   elementId,
                elementType: existing.dataset.type || '',
                pageId:      Impulse.pageId,
                device:      window.impulseDevice || 'desktop'
            }, '*');
        }
        
        function addElementToCellGridCell(type, cellGridId, row, col) {
            
            if (forbiddenInCells.indexOf(type) !== -1) {
                return;
            }
            addElement(type, cellGridId, -1, null, { row: row, col: col });
        }

        

        

        

        
        function wrapElementsInContainer(ids, kind) {
            if (!ids || ids.length < 1 || !Impulse.pageId) return;
            
            $.ajax({
                url: Impulse.api + 'elements/' + ids[0],
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(srcRow) {
                if (!srcRow) { window.showToast && window.showToast('Wrap failed: source missing', 'error'); return; }
                var origParentId  = srcRow.parent_id || null;
                var origSortOrder = parseInt(srcRow.sort_order, 10) || 0;

                
                var _n = ids.length;
                var containerType, containerSettings, childSettingsFor;
                if (kind === 'rows') {
                    containerType = 'rows';
                    var _rwRows = [];
                    for (var _r = 0; _r < _n; _r++) _rwRows.push({ widths: [100], cells: [[]] });
                    containerSettings = { rows: JSON.stringify(_rwRows), row_gap: 16, cell_gap: 16 };
                    childSettingsFor = function (i) { return { _cell_row: i, _cell_col: 0 }; };
                } else if (kind === 'columns') {
                    containerType = 'columns';
                    var _cw = Math.max(1, Math.round(100 / _n));
                    var _cols = [];
                    for (var _c = 0; _c < _n; _c++) _cols.push({ width: _cw, cells: [{ _empty: true }] });
                    containerSettings = { columns: JSON.stringify(_cols), col_gap: 16, cell_gap: 16 };
                    childSettingsFor = function (i) { return { _cell_col: i, _cell_row: 0 }; };
                } else if (kind === 'grid') {
                    containerType = 'grid';
                    var _gc = Math.ceil(Math.sqrt(_n));
                    var _gr = Math.ceil(_n / _gc);
                    containerSettings = { columns: _gc, rows: _gr, gap_horizontal: 16, gap_vertical: 16 };
                    childSettingsFor = function (i) { return {}; };
                } else { 
                    containerType = 'section';

                    

                    containerSettings = { bg_color: 'transparent', padding_top: 20, padding_bottom: 20, padding_left: 20, padding_right: 20, full_width: false, compact: 1 };
                    childSettingsFor = function (i) { return {}; };
                }
                var _kindLabel = (kind === 'rows') ? 'Rows' : (kind === 'columns') ? 'Columns' : (kind === 'grid') ? 'Grid' : 'Section';
                var doneLabel = ' in ' + _kindLabel;
                addElementWithSettings(containerType, containerSettings, origParentId, origSortOrder, function(newContainerId) {
                    if (!newContainerId) { window.showToast && window.showToast('Wrap failed', 'error'); return; }

                    
                    
                    function putNext(i) {
                        if (i >= ids.length) {
                            saveToHistory('wrap-selection', {
                                containerId: newContainerId,
                                ids: ids.slice(),
                                oldParentId: origParentId,
                                oldSortOrder: origSortOrder
                            });
                            refreshPreview();
                            setTimeout(updateStructureTree, 200);
                            openSettings(newContainerId, containerType);
                            window.showToast && window.showToast('Wrapped ' + ids.length + (ids.length === 1 ? ' block' : ' blocks') + doneLabel);
                            return;
                        }
                        $.ajax({
                            url: Impulse.api + 'elements/' + ids[i],
                            method: 'PUT',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            contentType: 'application/json',
                            data: JSON.stringify({
                                parent_id: newContainerId,
                                sort_order: i,
                                settings: childSettingsFor(i),
                                page_id: Impulse.pageId
                            })
                        }).always(function() { putNext(i + 1); });
                    }
                    putNext(0);
                });
            }).fail(function() {
                window.showToast && window.showToast('Wrap failed: read source', 'error');
            });
        }
        window.wrapElementsInContainer = wrapElementsInContainer;

        

        

        

        

        
        
        function convertHeadingToKinetic(id) {
            if (!id || !Impulse.pageId) return;
            if (window.showToast) showToast('Converting to Kinetic…');
            $.ajax({
                url: Impulse.api + 'elements/' + id,
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(el) {
                var t = el && (el.section_type || el.type);
                if (!el || t !== 'title') {
                    window.showToast && window.showToast('Convert failed: not a Title', 'error');
                    return;
                }
                var s = el.settings || {};
                
                var text   = (s.line_1 || s.la_text || s.text || '').toString();
                var tag    = s.tag || '';
                var color  = s.line_1_color || s.la_color || '';
                var font   = s.line_1_font  || s.font_family || '';
                var weight = s.line_1_weight || '';
                var line = { text: text, motion: 'rise' };
                if (font)   line.font   = font;
                if (weight) line.weight = String(weight);
                if (color)  line.color  = color;
                var newSettings = {
                    composition:  'block-slam',           
                    custom_mode:  '1',
                    custom_lines: JSON.stringify([line]),
                    tag:          (['h1','h2','h3'].indexOf(tag) > -1 ? tag : ''),
                    color:        color || '#ffffff',
                    loop:         '0',

                    

                    
                    lead_screen:  '0',

                    

                    
                    height_mode:  'fixed',
                    height:       '120'
                };
                if (s.align)         newSettings.align         = s.align;
                if (s.margin_bottom) newSettings.margin_bottom = s.margin_bottom;
                if (s.margin_top)    newSettings.margin_top    = s.margin_top;
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ element_type: 'kinetic', settings: newSettings, page_id: Impulse.pageId })
                }).done(function() {

                    
                    try {
                        viewportPreserve.capture();
                        viewportPreserve._elementId = id;
                    } catch (e) {}
                    refreshPreview();
                    setTimeout(updateStructureTree, 200);
                    if (selectedElementId == id) { try { openSettings(id, 'kinetic'); } catch (e) {} }
                    window.showToast && window.showToast('Converted to Kinetic');
                }).fail(function() {
                    window.showToast && window.showToast('Convert failed: type change', 'error');
                });
            }).fail(function() {
                window.showToast && window.showToast('Convert failed: load', 'error');
            });
        }

        function convertGridToRows(gridId) {
            console.log('[ConvertToRows] start, gridId=', gridId, 'pageId=', Impulse && Impulse.pageId);
            if (window.showToast) showToast('Converting grid…');
            if (!gridId || !Impulse.pageId) {
                console.warn('[ConvertToRows] missing gridId or pageId');
                if (window.showToast) showToast('Convert failed: missing IDs', 'error');
                return;
            }
            $.ajax({
                url: Impulse.api + 'elements/' + gridId,
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(grid) {
                console.log('[ConvertToRows] GET response:', grid);

                
                var gType = grid && (grid.section_type || grid.type);
                if (!grid || gType !== 'grid') {
                    window.showToast && window.showToast('Convert failed: not a Grid', 'error');
                    return;
                }
                var s = grid.settings || {};
                var cols = parseInt(s.columns) || 1;
                var rows = parseInt(s.rows) || 1;
                var gapH = parseInt(s.gap_horizontal) || 0;
                var gapV = parseInt(s.gap_vertical) || 0;
                
                var rowsArr = [];
                for (var r = 0; r < rows; r++) {
                    var widths = [];
                    var cells = [];
                    for (var c = 0; c < cols; c++) {
                        widths.push(Math.round(10000 / cols) / 100); 
                        cells.push({});
                    }
                    rowsArr.push({ widths: widths, cells: cells });
                }

                
                var lostFeatures = [];
                var idxToRC = function(idx) { return { r: Math.floor(idx / cols), c: idx % cols }; };
                var keyMap = {
                    'cell_bg_':                'bg_color',
                    'cell_border_color_':      'border_color',
                    'cell_border_width_':      'border_width',
                    'cell_border_top_':        'border_top',
                    'cell_border_right_':      'border_right',
                    'cell_border_bottom_':     'border_bottom',
                    'cell_border_left_':       'border_left',
                    'cell_halign_':            'halign',
                    'cell_valign_':            'valign',
                    'cell_pad_h_':             'padding_sides',
                };
                var lossKeys = ['cell_rotate_','cell_scale_','cell_bg_gradient_to_','cell_border_gradient_to_'];
                Object.keys(s).forEach(function(k) {
                    
                    if (/_(tablet|mobile)$/.test(k)) return;
                    var matched = false;
                    Object.keys(keyMap).forEach(function(prefix) {
                        if (matched) return;
                        if (k.indexOf(prefix) === 0) {
                            var idxStr = k.slice(prefix.length);
                            var idx = parseInt(idxStr);
                            if (isNaN(idx)) return;
                            var rc = idxToRC(idx);
                            if (rc.r >= rows || rc.c >= cols) return;
                            var dstKey = keyMap[prefix];
                            
                            if (/^border_(top|right|bottom|left)$/.test(dstKey)) {
                                rowsArr[rc.r].cells[rc.c][dstKey] = !(s[k] === '0' || s[k] === 0 || s[k] === false);
                            } else {
                                rowsArr[rc.r].cells[rc.c][dstKey] = s[k];
                            }
                            matched = true;
                        }
                    });
                    
                    if (!matched && k.indexOf('cell_pad_v_') === 0) {
                        var pIdx = parseInt(k.slice('cell_pad_v_'.length));
                        if (!isNaN(pIdx)) {
                            var prc = idxToRC(pIdx);
                            if (prc.r < rows && prc.c < cols) {
                                rowsArr[prc.r].cells[prc.c].padding_top = s[k];
                                rowsArr[prc.r].cells[prc.c].padding_bottom = s[k];
                            }
                        }
                        matched = true;
                    }
                    
                    if (!matched) {
                        for (var li = 0; li < lossKeys.length; li++) {
                            if (k.indexOf(lossKeys[li]) === 0 && s[k]) {
                                lostFeatures.push(lossKeys[li].replace(/_$/, ''));
                                break;
                            }
                        }
                    }
                });
                
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                    method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce }
                }).done(function(allElements) {

                    
                    var arr = (allElements && allElements.elements) || (Array.isArray(allElements) ? allElements : []);
                    var children = arr.filter(function(e) { return e.parent_id == gridId; });
                    
                    var pending = children.length;
                    var anyChildFail = false;
                    var afterChildren = function() {
                        
                        var newSettings = {
                            rows: JSON.stringify(rowsArr),
                            row_gap: gapV,
                            cell_gap: gapH
                        };
                        
                        if (s.margin_top)    newSettings.margin_top    = s.margin_top;
                        if (s.margin_bottom) newSettings.margin_bottom = s.margin_bottom;
                        $.ajax({
                            url: Impulse.api + 'elements/' + gridId,
                            method: 'PUT',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            contentType: 'application/json',
                            data: JSON.stringify({
                                element_type: 'rows',
                                settings: newSettings,
                                page_id: Impulse.pageId
                            })
                        }).done(function() {
                            refreshPreview();
                            setTimeout(updateStructureTree, 200);
                            var msg = 'Converted to Rows';
                            if (lostFeatures.length) {
                                var unique = lostFeatures.filter(function(v,i,a){return a.indexOf(v)===i;});
                                msg += ' (lost: ' + unique.join(', ') + ')';
                            }
                            window.showToast && window.showToast(msg);
                        }).fail(function() {
                            window.showToast && window.showToast('Convert failed: type change', 'error');
                        });
                    };
                    if (!pending) { afterChildren(); return; }
                    children.forEach(function(child) {
                        var idx = parseInt(child.sort_order) || 0;
                        var rc = idxToRC(idx);
                        $.ajax({
                            url: Impulse.api + 'elements/' + child.id,
                            method: 'PUT',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            contentType: 'application/json',
                            data: JSON.stringify({
                                settings: { _cell_row: rc.r, _cell_col: rc.c },
                                page_id: Impulse.pageId
                            })
                        }).always(function() {
                            pending--;
                            if (pending === 0) afterChildren();
                        }).fail(function() { anyChildFail = true; });
                    });
                }).fail(function() {
                    window.showToast && window.showToast('Convert failed: read children', 'error');
                });
            }).fail(function() {
                window.showToast && window.showToast('Convert failed: read source', 'error');
            });
        }
        window.convertGridToRows = convertGridToRows;

        function addElementWithSettings(type, settings, parentId, position, onCreated) {
            
            if (!Impulse.pageId) {
                console.error('Cannot add element: no page is open');
                return;
            }

            var _rootOverlay2 = ['section', 'header', 'footer', 'modal'];
            if ((Impulse.pageSettings && (true)) && _rootOverlay2.indexOf(type) === -1 && (!parentId || parentId === 0)) {
                var activeScreen = getActiveScreenId();
                if (activeScreen) {
                    parentId = activeScreen;
                } else {
                    return;
                }
            }

            
            var screenModeLayoutTypes = ['rows', 'columns']; 
            if ((Impulse.pageSettings && (true)) && parentId &&
                screenModeLayoutTypes.indexOf(type) !== -1) {
                try {
                    var iframeDoc = document.getElementById('impulse-iframe').contentDocument;
                    var parentEl  = iframeDoc && iframeDoc.querySelector('.impulse-el[data-id="' + parentId + '"]');
                    if (parentEl && parentEl.dataset.type === 'section') {
                        settings = $.extend({ fill_container: true }, settings);
                    }
                } catch(e) {}
            }

            var currentId = $('.impulse-panel-right').data('element-id');
            if (currentId && $('#impulse-settings-body').text().indexOf('Loading') === -1 && 
                !isPageSettingsMode()) {
                var currentSettings = collectSettingsFromPanel();
                $.ajax({
                    url: Impulse.api + 'elements/' + currentId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: currentSettings, page_id: Impulse.pageId }),
                    async: false
                });
            }
            
            var sortOrder = (position !== null && position !== undefined && !isNaN(position) && position >= 0) ? position : -1;
            
            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({
                    element_type: type,
                    parent_id: parentId || null,
                    sort_order: sortOrder,
                    settings: settings
                }),
                success: function(resp) {
                    if (resp.id && resp.id > 0) {
                        saveToHistory('add', {
                            elementId: resp.id,
                            elementType: type,
                            parentId: parentId,
                            sortOrder: resp.sort_order || sortOrder,
                            settings: resp.settings || settings || {}
                        });
                        pendingSelectElement = null;
                        var _injSlideIdx = (settings && settings.slide_index !== undefined) ? settings.slide_index : undefined;
                        injectNewElement(resp.id, type, onCreated, resp.sort_order || 0, null, null, null, _injSlideIdx);
                        setTimeout(updateStructureTree, 300);
                        if (!onCreated) window.showToast('Block added');

                    } else {
                        console.error('Insert failed:', resp.error);
                        window.showToast('Failed to insert template');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('addElementWithSettings error:', error);
                    window.showToast('Failed to insert template');
                }
            });
        }

        function addElementWithSettingsNearSibling(type, settings, siblingId, position, onCreated) {
            
            if (!Impulse.pageId) {
                console.error('Cannot add element: no page is open');
                return;
            }
            
            var currentId = $('.impulse-panel-right').data('element-id');
            if (currentId && $('#impulse-settings-body').text().indexOf('Loading') === -1 && 
                !isPageSettingsMode()) {
                var currentSettings = collectSettingsFromPanel();
                $.ajax({
                    url: Impulse.api + 'elements/' + currentId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: currentSettings, page_id: Impulse.pageId }),
                    async: false
                });
            }
            
            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({
                    element_type: type,
                    sibling_id: siblingId,
                    insert_position: position,
                    settings: settings
                }),
                success: function(resp) {
                    if (resp.id && resp.id > 0) {
                        saveToHistory('add', {
                            elementId: resp.id,
                            elementType: type,
                            siblingId: siblingId,
                            position: position,
                            parentId: resp.parent_id || 0,
                            sortOrder: resp.sort_order || 0,
                            settings: resp.settings || settings || {}
                        });
                        pendingSelectElement = null;
                        injectNewElement(resp.id, type, onCreated, resp.sort_order || 0, siblingId, position);
                        setTimeout(updateStructureTree, 300);
                        window.showToast('Block added');
                    } else {
                        console.error('Insert failed:', resp.error);
                        window.showToast('Failed to insert template');
                    }
                },
                error: function() {
                    window.showToast('Failed to insert template');
                }
            });
        }

        function addElementWithSettingsToCellGridCell(type, settings, cellGridId, row, col, onCreated) {
            
            if (forbiddenInCells.indexOf(type) !== -1) {
                return;
            }
            var mergedSettings = Object.assign({}, settings, {
                _cell_row: row,
                _cell_col: col
            });
            addElementWithSettings(type, mergedSettings, cellGridId, -1, onCreated);
        }

        
        
        $(document).on('change', 'input[type="checkbox"][name="chat_visible"]', function() {
            var chatOn = $(this).is(':checked');
            Impulse.pageSettings = Impulse.pageSettings || {};
            Impulse.pageSettings.chat_visible = chatOn ? 1 : 0;
            var previewIframe = document.getElementById('impulse-iframe');
            if (previewIframe && previewIframe.contentDocument) {
                var previewDoc = previewIframe.contentDocument;
                var chatEl = previewDoc.getElementById('instinctor-chat');
                if (chatEl) {
                    if (chatOn) { chatEl.classList.remove('chat-hidden'); chatEl.style.removeProperty('display'); }
                    else        { chatEl.classList.add('chat-hidden'); }
                }
                var barEl = previewDoc.getElementById('instinctor-chat-bar');
                if (barEl) {
                    if (chatOn) barEl.style.removeProperty('display');
                    else        barEl.style.setProperty('display','none','important');
                }
            }
            showSaveStatus(true);
            clearTimeout(pageSettingsSaveTimer);
            pageSettingsSaveTimer = setTimeout(function() {
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: Impulse.pageSettings }),
                    success: function() { showSaveStatus(); }
                });
            }, 300);
        });

        

        

        $(document).on('change', 'input[type="checkbox"][name="compact"]', function() {
            var on = $(this).is(':checked');
            $('.impulse-section-frosted-wrap').toggle(on);
            if (!on) {
                var $f = $('input[type="checkbox"][name="frosted_glass"]');
                if ($f.is(':checked')) {
                    $f.prop('checked', false).trigger('change');
                }
                
                $('.impulse-section-frosted-tune').css('display', 'none');
            }
        });

        

        $(document).on('change', 'input[type="checkbox"][name="frosted_glass"]', function() {
            $('.impulse-section-frosted-tune').css('display', $(this).is(':checked') ? 'contents' : 'none');
        });
        $(document).on('change', 'input[type="checkbox"][name="section_tilt"]', function() {
            var on = $(this).is(':checked');
            $('.impulse-section-tilt-settings').toggle(on);
            var _id  = $('.impulse-panel-right').data('element-id');
            var _ifr = document.getElementById('impulse-iframe');
            var _doc = _ifr && (_ifr.contentDocument || _ifr.contentWindow.document);
            var _sec = _doc && _doc.querySelector('.impulse-el[data-id="' + _id + '"] > section.impulse-section');
            if (_sec) {
                if (on) {
                    _sec.setAttribute('data-section-tilt', '1');
                    _sec.setAttribute('data-section-tilt-intensity', $('input[name="section_tilt_intensity"]').val() || '50');
                } else {
                    _sec.removeAttribute('data-section-tilt');
                    _sec.removeAttribute('data-section-tilt-intensity');
                    _sec.style.transform = '';
                }
                if (_ifr.contentWindow.ImpulseSectionFx && _ifr.contentWindow.ImpulseSectionFx.reinit) {
                    _ifr.contentWindow.ImpulseSectionFx.reinit();
                }
            }
            autoSaveAndPreview(false);
        });

        $(document).on('change', 'input[type="checkbox"][name="section_ambient_over_content"]', function() {
            var on = $(this).is(':checked');
            var _id  = $('.impulse-panel-right').data('element-id');
            var _ifr = document.getElementById('impulse-iframe');
            var _doc = _ifr && (_ifr.contentDocument || _ifr.contentWindow.document);
            var _sec = _doc && _doc.querySelector('.impulse-el[data-id="' + _id + '"] > section.impulse-section');
            if (!_sec) return;
            if (on) _sec.setAttribute('data-section-ambient-over', '1');
            else    _sec.removeAttribute('data-section-ambient-over');
            if (_ifr.contentWindow.ImpulseSectionFx && _ifr.contentWindow.ImpulseSectionFx.reinit) {
                _ifr.contentWindow.ImpulseSectionFx.reinit();
            }
        });

        
        $(document).on('input', 'input[name="section_tilt_intensity"], input[name="section_ambient_intensity"], input[name="section_ambient_hue"]', function() {
            var name = $(this).attr('name');
            var _id  = $('.impulse-panel-right').data('element-id');
            var _ifr = document.getElementById('impulse-iframe');
            var _doc = _ifr && (_ifr.contentDocument || _ifr.contentWindow.document);
            var _sec = _doc && _doc.querySelector('.impulse-el[data-id="' + _id + '"] > section.impulse-section');
            if (!_sec) return;
            var activeAttr, writeAttr;
            if (name === 'section_tilt_intensity') {
                activeAttr = 'data-section-tilt';
                writeAttr  = 'data-section-tilt-intensity';
            } else if (name === 'section_ambient_intensity') {
                activeAttr = 'data-section-ambient';
                writeAttr  = 'data-section-ambient-intensity';
            } else {
                activeAttr = 'data-section-ambient';
                writeAttr  = 'data-section-ambient-hue';
            }
            if (_sec.hasAttribute(activeAttr)) {
                _sec.setAttribute(writeAttr, $(this).val() || '');
                if (_ifr.contentWindow.ImpulseSectionFx && _ifr.contentWindow.ImpulseSectionFx.reinit) {
                    _ifr.contentWindow.ImpulseSectionFx.reinit();
                }
            }
        });

        

        

        

        
        
        $(document).on('click', '.impulse-btn-group button:not(.impulse-cloud-toggle):not(.impulse-border-side-btn):not(.impulse-cell-border-width-btn)', function() {
            var $group = $(this).closest('.impulse-btn-group');
            var $parent = $group.parent();
            var isToggleable = $group.attr('data-toggleable') === '1' || $parent.hasClass('impulse-btn-group-rows') && $parent.find('.impulse-btn-group[data-toggleable]').length;

            

            

            

            
            
            if ($group.data('name') === 'text_reveal') {
                var _trOff = $(this).hasClass('active'); 
                $group.find('button').removeClass('active');
                var _trVal;
                if (_trOff) {
                    _trVal = 'none';
                } else {
                    $(this).addClass('active');
                    _trVal = $(this).data('value');
                }
                $group.find('input[type="hidden"]').val(_trVal);
                $('.impulse-text-reveal-controls').toggle(_trVal !== 'none');
                var _trId = $('.impulse-panel-right').data('element-id');
                if (_trId) {
                    var _trExisting = $('.impulse-panel-right').data('existing-settings') || {};
                    var _trMerged   = $.extend({}, _trExisting, collectSettingsFromPanel(_trExisting));
                    $('.impulse-panel-right').data('existing-settings', _trMerged);
                    enqueueSave(_trId, _trMerged, function(ok) { if (ok && typeof showSaveStatus === 'function') showSaveStatus(); });
                }
                if (_trVal !== 'none' && typeof previewTextReveal === 'function') previewTextReveal();
                return;
            }

            if (isToggleable && $(this).hasClass('active')) {
                var toggleDefault = $group.data('toggle-default') || 'none';
                if ($parent.hasClass('impulse-btn-group-rows')) {
                    $parent.find('button').removeClass('active');
                    $parent.find('input[type="hidden"]').val(toggleDefault);
                } else {
                    $group.find('button').removeClass('active');
                    $group.find('input[type="hidden"]').val(toggleDefault);
                }
                
                if ($group.data('name') === 'screen_gradient_shape') {
                    $group.find('button').css('outline-color', 'transparent');
                    _liveUpdateGradientOverlay();
                    autoSavePageSettings(false);
                    return;
                }
                
                if ($group.data('name') === 'section_tilt' || $group.data('name') === 'section_ambient') {
                    try {
                        var _toId  = $('.impulse-panel-right').data('element-id');
                        var _toIfr = document.getElementById('impulse-iframe');
                        var _toDoc = _toIfr && (_toIfr.contentDocument || _toIfr.contentWindow.document);
                        var _toSec = _toDoc && (_toDoc.querySelector('.impulse-el[data-id="' + _toId + '"] > section.impulse-section') || _toDoc.querySelector('.impulse-el[data-id="' + _toId + '"] section'));
                        if (_toSec) {
                            if ($group.data('name') === 'section_tilt') {
                                _toSec.removeAttribute('data-section-tilt');
                                _toSec.removeAttribute('data-section-tilt-intensity');
                            } else {
                                _toSec.removeAttribute('data-section-ambient');
                                _toSec.removeAttribute('data-section-ambient-intensity');
                            }
                            _toSec.style.transform = '';
                            if (_toIfr.contentWindow && _toIfr.contentWindow.ImpulseSectionFx && _toIfr.contentWindow.ImpulseSectionFx.reinit) {
                                _toIfr.contentWindow.ImpulseSectionFx.reinit();
                            }
                        }
                    } catch (e) {}
                    if ($group.data('name') === 'section_tilt') {
                        $('.impulse-section-tilt-settings').hide();
                    } else {
                        $('.impulse-section-ambient-settings').hide();
                    }
                    autoSaveAndPreview(false);
                    return;
                }
                
                if ($group.data('name') === 'ovfx') {
                    $('.impulse-ovfx-settings').hide();
                    autoSaveAndRefresh();
                    return;
                }
                autoSaveAndPreview(true);
                return;
            }

            if ($parent.hasClass('impulse-btn-group-rows')) {
                $parent.find('.impulse-btn-group button').removeClass('active');
                $(this).addClass('active');
                
                $parent.find('input[type="hidden"]').val($(this).data('value'));
            } else {
                $group.find('button').removeClass('active');
                $(this).addClass('active');
                $group.find('input[type="hidden"]').val($(this).data('value'));
            }
            
            var groupName = $group.data('name');

            

            

            
            if (groupName === 'cell_valign' || groupName === 'cell_halign') {
                return;
            }
            
            if (groupName === 'align') {
                var _cacheId = $('.impulse-panel-right').data('element-id');
                if (_cacheId) {
                    if (!window._impulseAlignCache) window._impulseAlignCache = {};
                    window._impulseAlignCache[_cacheId] = $(this).data('value');
                }
            }

            

            
            
            if (groupName === 'gradient_overlay_type') {
                var _goLinear = $(this).data('value') === 'linear';
                $('.impulse-go-roundness-wrap').css('display', _goLinear ? 'none' : 'contents');
                autoSaveAndPreview(true);
                return;
            }

            

            if (groupName === 'screen_gradient_shape') {
                var _sgVal = $(this).data('value');
                var _sgAngle = $('.impulse-go-bar-angle, .impulse-page-overlay-angle');
                _sgAngle.css('display', _sgVal === 'linear' ? 'grid' : 'none');
                
                $(this).closest('.impulse-go-bar-shapes, .impulse-page-overlay-shapes').find('button').each(function() {
                    $(this).css('outline-color', $(this).data('value') === _sgVal ? ImpC.text : 'transparent');
                });
                
                var _c1 = $('input[name="screen_gradient_color1"]').val() || '';
                var _c2 = $('input[name="screen_gradient_color2"]').val() || '';
                var _isEmpty = function(c) { return !c || c === 'rgba(0,0,0,0)' || c === 'transparent'; };
                if (_isEmpty(_c1) && _isEmpty(_c2)) {
                    var _defaults = {
                        vignette: ['rgba(0,0,0,0.55)', 'rgba(0,0,0,0)'],
                        glow:     ['rgba(255,255,255,0.25)', 'rgba(0,0,0,0)'],
                        linear:   ['rgba(0,0,0,0.5)', 'rgba(0,0,0,0)'],
                        frame:    ['rgba(0,0,0,0.6)', 'rgba(0,0,0,0)']
                    };
                    var _def = _defaults[_sgVal] || ['rgba(0,0,0,0.5)', 'rgba(0,0,0,0)'];
                    
                    $('input[name="screen_gradient_color1"]').val(_def[0]);
                    $('input[name="screen_gradient_color2"]').val(_def[1]);
                }
                _liveUpdateGradientOverlay();
                autoSavePageSettings(false);
                return;
            }

            
            if (groupName === 'screen_transition') {
                var val = $(this).data('value');
                $('[data-name="screen_transition"] button').removeClass('active');
                $(this).addClass('active');
                $('input[name="screen_transition"]').val(val);
                
                $('.impulse-z-depth-options').css('display', ['z_depth','depth_spring','depth_vortex','depth_zoom'].indexOf(val)!==-1 ? 'contents' : 'none');
                
                var ifrm = document.getElementById('impulse-iframe');
                if (ifrm && ifrm.contentDocument && ifrm.contentDocument.body) {
                    ifrm.contentDocument.body.dataset.screenTransition = val;
                    var _wrapper2 = ifrm.contentDocument.querySelector('.impulse-screen-wrapper');
                    if (_wrapper2) _wrapper2.dataset.transition = val;
                }
                if (ifrm && ifrm.contentWindow && ifrm.contentWindow.ImpulseScreens) {
                    ifrm.contentWindow.ImpulseScreens.updateSettings(val);
                }
                autoSavePageSettings(false);
                return;
            }

            if (groupName === 'direction') {
                var isRow = $(this).data('value') === 'row';
                $group.closest('.impulse-section-tab-content').find('.impulse-section-wrap-toggle').toggle(isRow);
                autoSaveAndPreview(true);
                return;
            }

            if (groupName === 'section_animation_toggle') {
                var animEnabled = $(this).data('value') === '1' || $(this).data('value') === 1;
                $group.closest('.impulse-section-tab-content').find('.impulse-bg-animation-settings').toggle(animEnabled);
                autoSaveAndPreview(true);
                return;
            }

            if (groupName === 'bg_size') {
                var sizeVal = $(this).data('value');
                var id = $('.impulse-panel-right').data('element-id');
                var iframe = document.getElementById('impulse-iframe');
                var doc = iframe && iframe.contentDocument;

                var resetPos = '50% 50%';
                $('input[name="bg_position"]').val(resetPos);
                
                if (doc && id) {
                    var sectionEl = doc.querySelector('.impulse-el[data-id="' + id + '"] section.impulse-section');
                    if (sectionEl) {
                        sectionEl.style.backgroundSize = sizeVal;
                        sectionEl.style.backgroundPosition = resetPos;
                    }
                }
                
                $('.impulse-bg-position-grid').css('display', 'grid');
                
                if (showDots) {
                    $('.impulse-bg-pos-btn').css({background: 'rgba(0,0,0,0.25)'}).removeClass('active').find('svg').attr('stroke', 'rgba(255,255,255,0.7)');
                    $('.impulse-bg-pos-btn[data-pos="50% 50%"]').css({background: 'rgba(255,255,255,0.85)'}).addClass('active').find('svg').attr('stroke', ''+ImpC.surface2+'');
                }
                autoSaveAndPreview();
                return;
            }

            if (groupName === 'content_align' || groupName === 'valign') {
                
                var id = $('.impulse-panel-right').data('element-id');
                if (id) {
                    var val = $(this).data('value');
                    var iframe = document.getElementById('impulse-iframe');
                    var doc = iframe && iframe.contentDocument;
                    if (doc) {
                        if (groupName === 'content_align') {
                            var container = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-container');
                            var section = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-section');
                            if (container) {
                                var marginMap = { left: ['0', 'auto'], center: ['auto', 'auto'], right: ['auto', '0'] };
                                var m = marginMap[val] || marginMap.center;
                                container.style.marginLeft = m[0];
                                container.style.marginRight = m[1];
                            }
                            var caMap = { left: 'flex-start', center: 'center', right: 'flex-end' };
                            var caVal = caMap[val] || 'center';
                            if (section) section.style.setProperty('--impulse-ca', caVal);
                        } else if (groupName === 'valign') {
                            var container = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-container');
                            if (container) {
                                var valignMap = {top:'flex-start',center:'center',bottom:'flex-end',between:'space-between',around:'space-around',evenly:'space-evenly'};
                                container.style.justifyContent = valignMap[val] || 'flex-start';
                            }
                        }
                    }
                }
                autoSaveAndPreview(true);
                return;
            }

            if (groupName === 'layout' || groupName === 'menu_position') {
                autoSaveAndRefresh();
                return;
            }

            

            if ((groupName === 'columns' || groupName === 'rows') && selectedElementType === 'grid') {
                var _gridId = $('.impulse-panel-right').data('element-id');
                if (_gridId) {
                    var _gridExisting = $('.impulse-panel-right').data('existing-settings') || {};
                    var _gridSettings = collectSettingsFromPanel(_gridExisting);
                    var _gridMerged = $.extend({}, _gridExisting, _gridSettings);
                    $('.impulse-panel-right').data('existing-settings', _gridMerged);
                    enqueueSave(_gridId, _gridMerged, function(success) {
                        if (success) {
                            refreshElement(_gridId);

                            
                            
                            if (typeof openSettings === 'function') {
                                openSettings(_gridId, 'grid');
                            }
                        }
                    });
                }
                return;
            }

            if (groupName === 'columns') {
                
                var colVal = parseInt($(this).data('value')) || 1;
                var mwSlider = document.getElementById('ppc-maxwidth-slider');
                if (mwSlider) {
                    var newMin = colVal * 250;
                    var currentVal = parseInt(mwSlider.value) || 1200;
                    mwSlider.min = newMin;
                    if (currentVal < newMin) {
                        mwSlider.value = newMin;
                        $(mwSlider).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(newMin + 'px');
                    }
                }
                autoSaveAndRefresh();
                return;
            }

            if (groupName === 'la_content_type') {
                var laCtVal = $(this).data('value');
                $('.la-text-settings').toggle(laCtVal === 'text');
                $('.la-image-settings').toggle(laCtVal === 'image');
                setTimeout(impulse_la_postUpdate, 10);
                autoSaveAndPreview(false);
                return;
            }

            
            
            if (groupName === 'align' && selectedElementType === 'title' && ($('input[name="la_preset"]').val() || '')) {
                impulse_la_postUpdate();
                autoSaveAndPreview(false);
                return;
            }

            

            if (groupName === 'la_preset') {
                var $btn = $(this);
                var $group = $btn.closest('.impulse-btn-group');
                var newPreset = $btn.data('value');
                var currentVal = $('input[name="la_preset"]').val() || '';

                $group.find('button').removeClass('active');
                if (String(newPreset) !== String(currentVal)) {
                    $btn.addClass('active');
                } else {
                    newPreset = ''; 
                }
                $('input[name="la_preset"]').val(newPreset);

                

                if (selectedElementType === 'title' && newPreset) {
                    var $modeInput = $('input[name="dt_3d_mode"]');
                    if ($modeInput.length && $modeInput.val() !== 'flat') {
                        $modeInput.val('flat').trigger('change');
                        $('.impulse-hdr-mode button').removeClass('active');
                        $('.impulse-hdr-mode button[data-value="flat"]').addClass('active');
                    }
                    
                    $('input[name="depth_effects"]').val('');
                    $('input[name="stroke_enabled"]').val('');
                    $('input[name="depth_of_field"]').val('');
                    $('input[name="depth_shadow"]').val('');

                    

                    

                    

                    

                    

                    $('.impulse-hdr-mode, .impulse-hdr-bevel-row').css({opacity:0.35,'pointer-events':'none'});
                }
                if (selectedElementType === 'title' && !newPreset) {

                    
                    $('.impulse-hdr-mode, .impulse-hdr-bevel-row').css({opacity:'','pointer-events':''});
                }

                var _laId = $('.impulse-panel-right').data('element-id');

                

                

                

                
                var _hdrStructural = (selectedElementType === 'title')
                    && (!currentVal || !newPreset);
                if (_laId) {
                    var _laExisting = $('.impulse-panel-right').data('existing-settings') || {};
                    var _laSettings = collectSettingsFromPanel(_laExisting);
                    var _laMerged = $.extend({}, _laExisting, _laSettings);
                    $('.impulse-panel-right').data('existing-settings', _laMerged);
                    enqueueSave(_laId, _laMerged, function(ok) {
                        if (!ok) return;
                        showSaveStatus();

                        

                        if (_hdrStructural) {
                            refreshElement(_laId);
                        }
                    });
                }
                if (selectedElementType === 'title') {
                    if (!_hdrStructural) {

                        

                        
                        
                        impulse_la_postUpdate();
                    }
                    return;
                }

                
                impulse_la_postUpdate();
                return;
            }

            if (groupName === 'animation_type' || groupName === 'animation_type_row2' || groupName === 'animation_type_row3') {
                var animVal = $(this).data('value');
                $('.impulse-flip-direction-setting').toggle(['spring','cube'].indexOf(animVal) !== -1);
                $('.impulse-slide-direction-setting').toggle(animVal === 'push');
                autoSaveAndRefresh();
                return;
            }

            
            if (name.startsWith('la_svg_color_')) {
                
                var _map = {};
                $body.find('input[name^="la_svg_orig_"]').each(function() {
                    var _idx  = $(this).attr('name').replace('la_svg_orig_','');
                    var _orig = $(this).val();
                    var _rep  = $body.find('input[name="la_svg_color_' + _idx + '"]').val() || _orig;
                    if (_orig) _map[_orig] = _rep;
                });
                $body.find('input[name="la_svg_colors"]').val(JSON.stringify(_map));
            }
            
            if (name === 'la_gradient_to') {
                $('.la-grad-angle-row').css('display', val ? '' : 'none');
            }
            if (groupName === 'la_font_weight') {
                $group.find('input[type="hidden"]').trigger('change');
                autoSaveAndPreview();
                return;
            }

            if (groupName === 'flip_direction' || groupName === 'slide_direction') {
                autoSaveAndRefresh();
                return;
            }

            
            
            if (groupName === 'display_mode') {
                
                var elId = selectedElementId;
                var elType = selectedElementType;
                autoSaveAndRefresh();
                setTimeout(function() {
                    if (!elId || !elType) return;
                    var cachedSettings = $('.impulse-panel-right').data('existing-settings');
                    if (cachedSettings) {
                        
                        var merged = $.extend({}, cachedSettings, collectSettingsFromPanel(cachedSettings));
                        renderSettingsPanel(elType, merged);
                    }
                }, 350);
                return;
            }

            

            
            if (groupName === 'hover_effect' || groupName === 'image_fit' || groupName === 'continuous_effect' || groupName === 'view' || groupName === 'slider_effect' || groupName === 'chart_type' || groupName === 'chart_style' || groupName === 'chart_legend_pos' || groupName === 'chart_label_format' || groupName === 'chart_orientation' || groupName === 'data_align') {

                
                
                if (groupName === 'chart_type') {
                    var _newChType = $('.impulse-panel-right [data-name="chart_type"] button.active').data('value')
                                  || $('.impulse-panel-right input[name="chart_type"]').val();
                    if (_newChType === 'line') {
                        $('.impulse-panel-right input[name="chart_volume"]').prop('checked', false);
                    }
                }
                autoSaveAndRefresh();

                
                
                if (groupName === 'chart_type' || groupName === 'chart_style' || groupName === 'chart_orientation') {
                    var _chRebuildType = $('.impulse-panel-right').data('element-type');
                    if (_chRebuildType === 'chart') {
                        setTimeout(function() {
                            var _existing = $('.impulse-panel-right').data('existing-settings') || {};
                            var _fresh = collectSettingsFromPanel(_existing);
                            var _merged = $.extend({}, _existing, _fresh);
                            $('.impulse-panel-right').data('existing-settings', _merged);
                            $('#impulse-settings-body').html(buildSettingsForm('chart', _merged, []));
                            
                            initChartEntriesSortable();
                        }, 40);
                    }
                }
                return;
            }

            
            if (groupName === 'carousel_mode') {
                autoSaveAndRefresh();
                return;
            }

            

            

            if (groupName === 'ovfx' || groupName === 'ovfx_ease') {
                if (groupName === 'ovfx') {
                    var _ovVal = $(this).hasClass('active') ? ($(this).data('value') || '') : '';
                    $('.impulse-ovfx-settings').toggle(!!_ovVal);
                    if (_ovVal) {
                        $('.impulse-ovfx-sliders').html(buildOvfxSliders(_ovVal, {}));
                        $('.impulse-ovfx-swatches').css('display',
                            OVFX_FLAT.indexOf(_ovVal) !== -1 ? 'grid' : 'none');
                    }
                }
                applyOvfxLivePreview();
                autoSaveAndPreview(false);
                return;
            }

            
            
            if (groupName === 'section_tilt' || groupName === 'section_ambient') {
                var _isTilt = groupName === 'section_tilt';
                var _val = $(this).hasClass('active') ? ($(this).data('value') || '') : '';
                
                if (_isTilt) $('.impulse-section-tilt-settings').toggle(_val === '1' || _val === 1);
                else {
                    $('.impulse-section-ambient-settings').toggle(_val !== 'none' && _val !== '');

                    
                    
                    $('.impulse-section-ambient-hue-wrap').css('display',
                        (_val === 'pulse' || _val === 'spotlight' || _val === 'aurora') ? 'grid' : 'none');
                    $('.impulse-section-ambient-over-wrap').css('display',
                        (_val === 'shine' || _val === 'pulse' || _val === 'prism' || _val === 'aurora' || _val === 'spotlight') ? 'flex' : 'none');
                }

                try {
                    var _id  = $('.impulse-panel-right').data('element-id');
                    var _ifr = document.getElementById('impulse-iframe');
                    var _doc = _ifr && (_ifr.contentDocument || _ifr.contentWindow.document);
                    
                    var _secEl = _doc && _doc.querySelector('.impulse-el[data-id="' + _id + '"] > section.impulse-section');
                    if (!_secEl) _secEl = _doc && _doc.querySelector('.impulse-el[data-id="' + _id + '"] section');
                    if (_secEl) {
                        if (_isTilt) {
                            if (_val === '1' || _val === 1) {
                                _secEl.setAttribute('data-section-tilt', '1');
                                var _ti = $('input[name="section_tilt_intensity"]').val() || '50';
                                _secEl.setAttribute('data-section-tilt-intensity', _ti);
                            } else {
                                _secEl.removeAttribute('data-section-tilt');
                                _secEl.removeAttribute('data-section-tilt-intensity');
                                _secEl.style.transform = '';
                            }
                        } else {
                            if (_val && _val !== 'none') {
                                _secEl.setAttribute('data-section-ambient', _val);
                                var _ai = $('input[name="section_ambient_intensity"]').val() || '50';
                                _secEl.setAttribute('data-section-ambient-intensity', _ai);
                                var _ah = $('input[name="section_ambient_hue"]').val() || '200';
                                _secEl.setAttribute('data-section-ambient-hue', _ah);
                                var _ao = $('input[name="section_ambient_over_content"]').is(':checked') ? '1' : '';
                                if (_ao) _secEl.setAttribute('data-section-ambient-over', '1');
                                else     _secEl.removeAttribute('data-section-ambient-over');
                            } else {
                                _secEl.removeAttribute('data-section-ambient');
                                _secEl.removeAttribute('data-section-ambient-intensity');
                                _secEl.removeAttribute('data-section-ambient-hue');
                                _secEl.removeAttribute('data-section-ambient-over');
                                _secEl.style.transform = '';
                            }
                        }
                        
                        if (_ifr.contentWindow && _ifr.contentWindow.ImpulseSectionFx && _ifr.contentWindow.ImpulseSectionFx.reinit) {
                            _ifr.contentWindow.ImpulseSectionFx.reinit();
                        }
                    }
                } catch (e) {}
                
                autoSaveAndPreview(false);
                return;
            }

            if (groupName === 'tiles_expand') {
                var _teId = $('.impulse-panel-right').data('element-id');
                var _teIframe = document.getElementById('impulse-iframe');
                if (_teIframe && _teIframe.contentDocument && _teId) {
                    var _teCont = _teIframe.contentDocument.querySelector('.impulse-el[data-id="' + _teId + '"] .impulse-acc-tiles');
                    if (_teCont) _teCont.dataset.expand = $(this).data('value');
                }
                autoSaveAndPreview(true);
                return;
            }

            

            

            if ($parent.hasClass('impulse-acc-anim-rows')) {
                var _accId = selectedElementId;
                var _accType = selectedElementType;
                var _accExisting = $('.impulse-panel-right').data('existing-settings') || {};
                var _accSettings = collectSettingsFromPanel(_accExisting);
                var _accMerged = $.extend({}, _accExisting, _accSettings);
                showSaveStatus(true);
                enqueueSave(_accId, _accMerged, function(success) {
                    if (!success) return;
                    if ($('.impulse-panel-right').data('element-id') == _accId) {
                        $('.impulse-panel-right').data('existing-settings', _accMerged);
                    }
                    showSaveStatus();
                    if (typeof refreshElement === 'function') {
                        refreshElement(_accId);
                    }

                    

                    

                    if (_accId && _accType) {
                        setTimeout(function() {
                            selectedElementId   = _accId;
                            selectedElementType = _accType;
                            try {
                                var _ifr = document.getElementById('impulse-iframe');
                                var _idoc = _ifr && (_ifr.contentDocument || _ifr.contentWindow.document);
                                if (_idoc) {
                                    _idoc.querySelectorAll('.impulse-el.selected').forEach(function(x) {
                                        x.classList.remove('selected');
                                    });
                                    var _el = _idoc.querySelector('.impulse-el[data-id="' + _accId + '"]');
                                    if (_el) _el.classList.add('selected');
                                }
                            } catch (_e) {}
                            openSettings(_accId, _accType);
                        }, 700);
                    }
                });
                return;
            }

            

            
            
            if (groupName === 'mode' && selectedElementType === 'marquee') {
                var _mqId = selectedElementId, _mqType = selectedElementType;
                var _mqNewMode = $(this).data('value');
                var _mqExisting = $('.impulse-panel-right').data('existing-settings') || {};
                var _mqCur = collectSettingsFromPanel(_mqExisting);
                _mqCur.mode = _mqNewMode;
                var _mqCards = _mqCur.cards;
                if (typeof _mqCards === 'string') { try { _mqCards = JSON.parse(_mqCards); } catch (e) { _mqCards = null; } }
                if (!impulseMarqueeCardsMatchMode(_mqCards, _mqNewMode)) {
                    var _mqStarter = impulseMarqueeStarterCards(_mqNewMode);
                    var _mqRc = parseInt(_mqCur.row_count, 10) || 2;
                    if (_mqRc < 1) _mqRc = 1;
                    _mqStarter.forEach(function (card, i) { card.row = i % _mqRc; });
                    _mqCur.cards = JSON.stringify(_mqStarter);
                }
                var _mqMerged = $.extend({}, _mqExisting, _mqCur);
                $('.impulse-panel-right').data('existing-settings', _mqMerged);
                showSaveStatus(true);
                enqueueSave(_mqId, _mqMerged, function (ok) {
                    if (!ok) return;
                    showSaveStatus();
                    if (typeof refreshElement === 'function') refreshElement(_mqId);
                    if (_mqId && _mqType) setTimeout(function () { openSettings(_mqId, _mqType); }, 450);
                });
                return;
            }

            

            
            if (groupName === 'row_count' && selectedElementType === 'marquee') {
                var _mrId = selectedElementId;
                var _mrN = parseInt($(this).data('value'), 10) || 1;
                if (_mrN < 1) _mrN = 1;
                $('.impulse-mq-cards-list .impulse-mq-card-item').each(function (i) {
                    $(this).find('.mq-card-row').val(String(i % _mrN));
                });
                if (typeof updateMarqueeCardsJSON === 'function') updateMarqueeCardsJSON();
                var _mrExisting = $('.impulse-panel-right').data('existing-settings') || {};
                var _mrMerged = $.extend({}, _mrExisting, collectSettingsFromPanel(_mrExisting));
                $('.impulse-panel-right').data('existing-settings', _mrMerged);
                showSaveStatus(true);
                enqueueSave(_mrId, _mrMerged, function (ok) {
                    if (!ok) return;
                    showSaveStatus();
                    if (typeof refreshElement === 'function') refreshElement(_mrId);
                });
                return;
            }

            

            

            
            if (groupName === 'align' && selectedElementType === 'text') {
                if (($('input[name="box_align"]').val() || '') === '') {
                    var _taExisting = $('.impulse-panel-right').data('existing-settings') || {};
                    var _taFreeze = _taExisting.box_align || _taExisting.align || 'center';
                    if (_taFreeze === 'justify') _taFreeze = 'left';
                    $('input[name="box_align"]').val(_taFreeze);
                    var $taBox = $('.impulse-btn-group[data-name="box_align"]');
                    $taBox.find('button').removeClass('active');
                    $taBox.find('button[data-value="' + _taFreeze + '"]').addClass('active');
                }
                autoSaveAndPreview(true);
                return;
            }

            autoSaveAndPreview(true);

            
            
            if ($group.data('refresh-panel')) {
                var _rpId = selectedElementId, _rpType = selectedElementType;
                var _rpExisting = $('.impulse-panel-right').data('existing-settings') || {};
                var _rpCurrent  = collectSettingsFromPanel(_rpExisting);
                $('.impulse-panel-right').data('existing-settings', $.extend({}, _rpExisting, _rpCurrent));
                setTimeout(function() { if (_rpId) openSettings(_rpId, _rpType); }, 250);
            }
        });

        

        

        $(document).on('click', '.impulse-border-side-btn', function(e) {

            if ($(this).closest('.impulse-cell-settings-section').length) return;
            var $btn = $(this);
            var $input = $btn.next('input[type="hidden"]');
            var stored = $input.val();
            var wasOn = !(stored === '0' || stored === 0 || stored === false);
            var newVal = wasOn ? '0' : '1';
            $input.val(newVal);
            $btn.attr('data-stored', newVal);
            var $wrapper = $btn.closest('.impulse-cell-border-cell');
            if ($wrapper.length) {
                
                var $widthInput = $wrapper.find('input[name^="cell_border_width_"]');
                var cw = parseInt($widthInput.val()) || 0;

                
                
                if (cw === 0 && !wasOn) {
                    cw = 1;
                    $widthInput.val('1');
                    $wrapper.find('.impulse-cell-border-width-btn').removeClass('active');
                    $wrapper.find('.impulse-cell-border-width-btn[data-width="1"]').addClass('active');
                    
                    $wrapper.find('.impulse-border-side-btn').each(function() {
                        $(this).toggleClass('active', $(this).attr('data-stored') === '1');
                    });
                }
                
                $btn.toggleClass('active', cw > 0 && !wasOn);

                
                var _cIdx = parseInt($wrapper.attr('data-cell-idx'), 10);
                if (!isNaN(_cIdx) && typeof _gridCellApplyBorderInline === 'function') {
                    _gridCellApplyBorderInline(_cIdx);
                }
            } else {
                
                $btn.toggleClass('active', !wasOn);
            }
            autoSaveAndPreview(true);
        });

        $(document).on('click', '.impulse-go-add-color2', function() {
            var $wrap = $(this).closest('.impulse-go-color2-wrap');
            var defaultColor = $('input[name="gradient_overlay_color1"]').val() || 'rgba(0,0,0,0.5)';
            $wrap.html(settingColorSwatchOnly('gradient_overlay_color2', defaultColor) + '<button type="button" class="impulse-go-remove-color2" style="width:16px;height:16px;border:none;background:none;color:'+ImpC.dim+';cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>');
            initColorPickers($wrap[0]);
            autoSaveAndPreview(true);
        });
        $(document).on('click', '.impulse-go-remove-color2', function() {
            var $wrap = $(this).closest('.impulse-go-color2-wrap');
            $wrap.html('<button type="button" class="impulse-go-add-color2" style="width:22px;height:22px;border:1px solid '+ImpC.border+';background:'+ImpC.panel+';color:'+ImpC.dim+';cursor:pointer;border-radius:3px;padding:0;display:flex;align-items:center;justify-content:center" title="Add second color"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg></button><input type="hidden" name="gradient_overlay_color2" value="rgba(0,0,0,0)">');
            autoSaveAndPreview(true);
        });
        
        $(document).on('click', '.impulse-go-bar-add-color2', function() {
            var $wrap = $(this).closest('.impulse-go-bar-color2-wrap');
            var defC = $('input[name="screen_gradient_color1"]').val() || 'rgba(255,255,255,0.3)';
            $wrap.html('<div class="impulse-color-setting impulse-color-swatch-only" data-name="screen_gradient_color2" style="display:block;margin:0;width:26px;height:26px"><div class="impulse-color-row" style="height:26px"><div class="impulse-color-swatch" style="--swatch-color:' + defC + ';width:26px;height:26px;min-width:26px;min-height:26px"></div><input type="hidden" name="screen_gradient_color2" value="' + defC + '" class="impulse-color-text"></div></div><button type="button" class="impulse-go-bar-remove-color2" style="width:14px;height:14px;border:none;background:none;color:'+ImpC.dim+';cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center"><svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>');
            initColorPickers($wrap[0]);
            autoSavePageSettings(false);
        });
        $(document).on('click', '.impulse-go-bar-remove-color2', function() {
            var $wrap = $(this).closest('.impulse-go-bar-color2-wrap');
            $wrap.html('<button type="button" class="impulse-go-bar-add-color2" style="width:22px;height:22px;border:1px solid '+ImpC.border+';background:'+ImpC.panel+';color:'+ImpC.dim+';cursor:pointer;border-radius:3px;padding:0;display:flex;align-items:center;justify-content:center"><svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg></button><input type="hidden" name="screen_gradient_color2" value="rgba(0,0,0,0)">');
            autoSavePageSettings(false);
        });

        var _laInitializing = false; 

        
        
        var _hdrLiveSel = '#impulse-settings-body input[name="line_1"], '
                        + '#impulse-settings-body textarea[name="line_1"], '
                        + '#impulse-settings-body input[name="line_1_size"], '
                        + '#impulse-settings-body input[name="line_1_color"], '
                        + '#impulse-settings-body input[name="line_1_grad_1"], '
                        + '#impulse-settings-body input[name="line_1_grad_2"], '
                        + '#impulse-settings-body input[name="line_1_grad_angle"], '
                        + '#impulse-settings-body input[name="line_1_weight"], '
                        + '#impulse-settings-body input[name="line_1_fill"], '
                        + '#impulse-settings-body input[name="line_1_font"], '
                        + '#impulse-settings-body input[name="font_family"], '
                        + '#impulse-settings-body input[name="letter_spacing"], '
                        + '#impulse-settings-body input[name="margin_bottom"], '

                        

                        

                        
                        + '#impulse-settings-body input[name="mouse_sens"]';
        $(document).on('change input', _hdrLiveSel, function() {
            if (selectedElementType !== 'title') return;
            if (_laInitializing) return;

            var _curPreset = $('#impulse-settings-body input[name="la_preset"]').val() || '';
            if (!_curPreset) return;
            impulse_la_postUpdate();
            autoSaveAndPreview(false);
        });

        
        $(document).on('change input', '#impulse-settings-body input[name="font_family"]', function() {
            if (selectedElementType !== 'title' || !($('input[name="la_preset"]').val() || '')) return;
            if (_laInitializing) return;
            impulse_la_postUpdate();
            autoSaveAndPreview(false);
        });

        

        

        

        $(document).on('click', '.impulse-btn-group[data-name="align"] button', function() {
            if (selectedElementType !== 'title') return;
            if (_laInitializing) return;

            var _p = $('#impulse-settings-body input[name="la_preset"]').val() || '';
            if (selectedElementType === 'title' && !_p) return;

            

            
            
            var _alElId = $('.impulse-panel-right').data('element-id');
            var _alIfr  = document.getElementById('impulse-iframe');
            if (_alIfr && _alIfr.contentWindow && _alElId) {
                _alIfr.contentWindow.postMessage({
                    type: 'la_update',
                    id: 'la-' + _alElId,
                    align: ($('#impulse-settings-body input[name="align"]').val() || 'center')
                }, '*');
            }
        });
        $(document).on('change input', '#impulse-settings-body input[name^="la_"], #impulse-settings-body textarea[name^="la_"]', function() {
            if (selectedElementType !== 'title') return;
            if (_laInitializing) return; 
            var name = $(this).attr('name');
            
            if (name && name.startsWith('la_svg_color_')) {
                var $b = $('#impulse-settings-body'), _map = {};
                $b.find('input[name^="la_svg_orig_"]').each(function() {
                    var _i = $(this).attr('name').replace('la_svg_orig_','');
                    var _o = $(this).val();
                    var _r = $b.find('input[name="la_svg_color_' + _i + '"]').val() || _o;
                    if (_o) _map[_o] = _r;
                });
                $b.find('input[name="la_svg_colors"]').val(JSON.stringify(_map));
            }

            

            if (selectedElementType === 'title') {
                impulse_la_postUpdate();
                autoSaveAndPreview(false);
                return;
            }
            impulse_la_postUpdate();
            
            autoSaveAndPreview(false);
        });
        var _laPostUpdating = false; 
        function impulse_la_postUpdate() {
            if (_laPostUpdating) return;
            _laPostUpdating = true;
            var _iframe = document.getElementById('impulse-iframe');
            if (!_iframe || !_iframe.contentWindow) { _laPostUpdating = false; return; }
            var $body = $('#impulse-settings-body');
            var currentPreset = $body.find('input[name="la_preset"]').val() || '';
            var elementId = $('.impulse-panel-right').data('element-id');
            var msg = { type: 'la_update', id: elementId ? 'la-' + elementId : null };

            
            
            var _isHdr = !($('input[name="la_preset"]').val() || ''); 
            var _readVal = function(heading, animator, fallback) {

                

                var $pri = $body.find('input[name="' + (_isHdr ? heading : animator) + '"]');
                if (!$pri.length) $pri = $body.find('input[name="' + (_isHdr ? animator : heading) + '"]');
                var v = $pri.val();
                return (v === undefined || v === '') ? fallback : v;
            };

            

            
            
            var _fsIn = $body.find('input[name="' + (_isHdr ? 'line_1_size' : 'la_font_size') + '"]');
            if (!_fsIn.length) _fsIn = $body.find('input[name="' + (_isHdr ? 'la_font_size' : 'line_1_size') + '"]');
            var _fsInput = _fsIn.val();
            if (_fsInput !== undefined && _fsInput !== '') msg.fontSize = _fsInput;

            

            

            
            (function(){
                var _laDev = window.impulseDevice || 'desktop';
                if (_laDev === 'desktop') return;
                if (typeof resolveDeviceSettings !== 'function' || typeof autoMobileDefaults !== 'function') return;
                try {
                    var _exS = $('.impulse-panel-right').data('existing-settings') || {};
                    var _rdS = autoMobileDefaults(resolveDeviceSettings(_exS, _laDev), 'title', _laDev);
                    var _fsKey = _isHdr ? 'line_1_size' : 'la_font_size';
                    if (_rdS && _rdS[_fsKey] !== undefined && _rdS[_fsKey] !== '' && _rdS[_fsKey] !== null) {
                        msg.fontSize = String(_rdS[_fsKey]);
                    }
                } catch (_e) {}
            })();
            msg.fontWeight  = _readVal('line_1_weight', 'la_font_weight', '700');
            
            var _hdrFill = ($body.find('input[name="line_1_fill"]').val() || 'solid');
            var _hdrColor;
            var _laColIn = $body.find('input[name="la_color"]');
            if (_laColIn.length) {
                
                _hdrColor = _laColIn.val() || '#ffffff';
            } else {

                

                _hdrColor = _hdrFill === 'gradient'
                    ? ($body.find('input[name="line_1_grad_1"]').val() || $body.find('input[name="line_1_color"]').val() || '#ffffff')
                    : ($body.find('input[name="line_1_color"]').val() || '#ffffff');
            }
            msg.color       = _hdrColor;
            msg.fontFamily  = $body.find('input[name="line_1_font"]').val()
                || $body.find('input[name="font_family"]').val() || '';
            msg.spring      = $body.find('input[name="la_spring"]').val() || '5';
            msg.imageWidth  = $body.find('input[name="la_image_width"]').val() || '280';

            

            

            

            var _line1Input  = $body.find('input[name="line_1"], textarea[name="line_1"]');
            var _laTextInput = $body.find('input[name="la_text"], textarea[name="la_text"]');
            msg.text        = _line1Input.length
                ? (_line1Input.val() || '')
                : (_laTextInput.val() || '');
            msg.contentType = $body.find('input[name="la_content_type"]').val() || 'text';
            msg.imageSrc    = $body.find('input[name="la_image_src"]').val() || '';
            msg.svgColors   = $body.find('input[name="la_svg_colors"]').val() || '';

            

            
            
            var _laTiltIn   = $body.find('input[name="la_tilt"]');
            msg.tilt        = _laTiltIn.length
                ? (_laTiltIn.val() || '0')
                : String(Math.min(50, Math.max(0, parseInt($body.find('input[name="mouse_sens"]').val()) || 0)));
            msg.depth       = $body.find('input[name="la_depth"]').val() || '50';
            
            var _gapIn      = $body.find('input[name="margin_bottom"]');
            if (!_gapIn.length) _gapIn = $body.find('input[name="la_gap_below"]');
            msg.gapBelow    = _gapIn.val() || '0';
            msg.align       = $body.find('input[name="align"]').val() || 'center';
            
            msg.gradientFrom  = _hdrColor;
            var _gtoIn = $body.find('input[name="la_gradient_to"]');
            if (_gtoIn.length) {
                msg.gradientTo    = _gtoIn.val() || '';
                msg.gradientAngle = parseInt($body.find('input[name="la_gradient_angle"]').val()) || 135;
            } else {
                msg.gradientTo    = _hdrFill === 'gradient'
                    ? ($body.find('input[name="line_1_grad_2"]').val() || '')
                    : '';
                msg.gradientAngle = parseInt($body.find('input[name="line_1_grad_angle"]').val()) || 135;
            }
            
            var _ls = $body.find('input[name="letter_spacing"]').val();
            if (_ls !== undefined && _ls !== '') msg.letterSpacing = parseInt(_ls);

            if (currentPreset) {
                msg.preset      = currentPreset;
                msg.duration    = Math.round(parseFloat($body.find('input[name="la_duration"]').val()||1.2)*1000);
                msg.delay       = Math.round(parseFloat($body.find('input[name="la_delay"]').val()||0)*1000);
                msg.scrollTrigger = '1';
                msg.flash       = $body.find('input[name="la_flash"]').is(':checked') ? '1' : '0';
            }
            _iframe.contentWindow.postMessage(msg, '*');

            

            
            try {
                var _doc = _iframe.contentDocument || _iframe.contentWindow.document;
                var _elId = msg.id;
                var _animEl = _elId ? _doc.getElementById(_elId) : _doc.querySelector('.impulse-logo-animator');
                if (_animEl) {
                    
                    if (msg.align !== undefined) {
                        var _safeAlign = (msg.align === 'left' || msg.align === 'right' || msg.align === 'center')
                            ? msg.align
                            : 'center';
                        _animEl.style.justifyContent = _safeAlign === 'left'
                            ? 'flex-start'
                            : (_safeAlign === 'right' ? 'flex-end' : 'center');

                        

                        
                        var _assetAlignEl = _animEl.querySelector('.impulse-la-asset');
                        if (_assetAlignEl && _assetAlignEl.tagName !== 'IMG') {
                            _assetAlignEl.style.textAlign = _safeAlign;
                        }
                    }
                    var _assetEl = _animEl.querySelector('.impulse-la-asset');
                    if (_assetEl && _assetEl.tagName !== 'IMG') {

                        
                        if (typeof msg.text === 'string') {
                            var _txEsc = document.createElement('div');
                            _txEsc.textContent = msg.text;
                            _assetEl.innerHTML = _txEsc.innerHTML
                                .replace(/&amp;nbsp;/g, '&nbsp;')
                                .replace(/&lt;(\/?(?:br|b|i|u|strong|em|sup|sub|small|mark))\s*\/?&gt;/gi,
                                    function(_m, tag) { return '<' + tag.toLowerCase() + '>'; })
                                .replace(/\r\n|\n/g, '<br>');
                        }
                        if (msg.fontSize)   _assetEl.style.fontSize = msg.fontSize + 'px';
                        if (msg.fontWeight) _assetEl.style.fontWeight = msg.fontWeight;
                        if (msg.fontFamily) _assetEl.style.fontFamily = "'" + msg.fontFamily + "', sans-serif";
                        if (msg.letterSpacing !== undefined) _assetEl.style.letterSpacing = parseInt(msg.letterSpacing) + 'px';

                        var _gt = msg.gradientTo || '';
                        var _gf = msg.gradientFrom || msg.color || '#1d2327';

                        

                        

                        

                        

                        var _isHeadingMsg = (typeof selectedElementType !== 'undefined' && selectedElementType === 'title');
                        var _hasRealGradient = _gt && _gf && _gf !== '#1d2327';
                        if (_hasRealGradient) {
                            _assetEl.style.backgroundImage = 'linear-gradient(' + ((msg.gradientAngle + 90) % 360) + 'deg,' + _gf + ',' + _gt + ')';
                            _assetEl.style.webkitBackgroundClip = 'text';
                            _assetEl.style.backgroundClip = 'text';
                            _assetEl.style.color = 'transparent';
                            _assetEl.style.webkitTextFillColor = 'transparent';
                        } else if (!_isHeadingMsg) {

                            
                            
                            _assetEl.style.backgroundImage = '';
                            _assetEl.style.webkitBackgroundClip = '';
                            _assetEl.style.backgroundClip = '';
                            _assetEl.style.color = msg.color || '#1d2327';
                            _assetEl.style.webkitTextFillColor = '';
                        }

                        

                        
                        var _cv = _animEl.querySelector('.impulse-la-canvas');
                        var _cwFn = _iframe.contentWindow && _iframe.contentWindow.sampleLogo;
                        if (_cv && _cwFn) {
                            try {

                                

                                

                                var _cw2 = _animEl.offsetWidth || 400, _ch2 = _animEl.offsetHeight || 200;
                                var _bg  = _iframe.contentWindow.getComputedStyle(_animEl).backgroundColor;
                                var _ah  = _assetEl.offsetHeight || _ch2;
                                var _by  = Math.max(0, Math.round((_ch2 - _ah) / 2));
                                var _bounds = { x: 0, y: _by, w: _cw2, h: Math.min(_ah, _ch2), bg: _bg };
                                var _gOpts = (_gf && _gt) ? { gradFrom: _gf, gradTo: _gt, gradAngle: (msg.gradientAngle || 135) } : null;
                                var _fresh = _cwFn(_assetEl, _cw2, _ch2, _bg, _bounds, _gOpts);
                                var _ctx = _cv.getContext('2d');

                                

                                
                                _ctx.globalAlpha = 1;
                                _ctx.globalCompositeOperation = 'source-over';
                                _ctx.filter = 'none';
                                _ctx.clearRect(0, 0, _cv.width, _cv.height);
                                _ctx.drawImage(_fresh, 0, 0);
                            } catch (_sampErr) {}
                        }
                    }
                }
            } catch (_laDomErr) {}

            _laPostUpdating = false;
        }

        $(document).on('input', 'input[name$="border_width"]', function() {
            if ($(this).closest('.impulse-cell-settings-section').length) return; 
            var val = parseInt($(this).val()) || 0;
            var $sides = $(this).closest('.impulse-setting-row').parent().siblings('.impulse-border-sides');
            if ($sides.length) {
                $sides.css('display', val > 0 ? 'flex' : 'none');
            }
        });

        

        

        

        
        $(document).on('click', '.impulse-btn-group[data-name="dt_3d_mode"] button', function() {
            var mode = $(this).data('value');
            var depthOn  = (mode === 'depth' || mode === 'outline_depth');
            var strokeOn = (mode === 'outline' || mode === 'outline_depth');
            $('input[name="depth_effects"]').val(depthOn ? '1' : '');
            $('input[name="stroke_enabled"]').val(strokeOn ? '1' : '');
            $('input[name="depth_of_field"]').val(depthOn ? '1' : '');
            $('input[name="depth_shadow"]').val(depthOn ? '1' : '');
            
            $('input[name="stroke_bevel"]').val(strokeOn ? '1' : '');

            

            var $rightPanel = $('.impulse-panel-right');
            var elId = $rightPanel.data('element-id');
            var settings = $.extend({}, $rightPanel.data('existing-settings') || {});
            $('#impulse-settings-body input[name], #impulse-settings-body select[name], #impulse-settings-body textarea[name]').each(function() {
                var $f = $(this);
                var k = $f.attr('name');
                if (!k) return;
                if (this.type === 'checkbox') settings[k] = this.checked ? '1' : '';
                else settings[k] = $f.val();
            });
            settings.dt_3d_mode = mode;
            settings.depth_effects  = depthOn  ? '1' : '';
            settings.stroke_enabled = strokeOn ? '1' : '';
            settings.depth_of_field = depthOn  ? '1' : '';
            settings.depth_shadow   = depthOn  ? '1' : '';
            settings.stroke_bevel   = strokeOn ? '1' : '';

            
            
            settings.la_preset = '';
            $('input[name="la_preset"]').val('');
            $('.impulse-btn-group[data-name="la_preset"] button').removeClass('active');
            if (typeof renderSettingsPanel === 'function') {
                renderSettingsPanel('title', settings);
            }
            
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });

        

        $(document).on('click', '.impulse-btn-group[data-name="stroke_spin_mode"] button', function() {
            var $btn = $(this);
            var mode = $btn.data('value');
            var $group = $btn.closest('.impulse-btn-group');
            $group.find('button').removeClass('active');
            $btn.addClass('active');
            $group.parent().find('input[name="stroke_spin_mode"]').val(mode);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });

        

        $(document).on('click', '.impulse-btn-group[data-name="orientation"] button', function() {
            var $body = $('#impulse-settings-body');
            var $horizSlot = $body.find('.divider-horiz-only');
            var $vertSlot  = $body.find('.divider-vert-only');
            if (!$horizSlot.length || !$vertSlot.length) return;
            var orient = $(this).data('value');
            $horizSlot.toggle(orient === 'horizontal');
            $vertSlot.toggle(orient === 'vertical');
        });

        $(document).on('click', '.impulse-btn-group[data-name="tab_style"] button', function() {
            var tabStyle = $(this).data('value');
            if (tabStyle === 'horizontal') {
                $('.impulse-tabs-radius-settings').show();
            } else {
                
                $('.impulse-tabs-radius-settings').hide();
                $('.impulse-tabs-radius-settings input[name="border_radius"]').val(0);
                $('.impulse-tabs-radius-settings .impulse-slider-value').text('0px');
            }
        });

        

        
        $(document).on('click', '.impulse-checkout-preset button', function() {
            var preset = $(this).data('value');
            var presets = {
                modern: {
                    colors: { button: ''+ImpC.surface2+'', button_text: '#ffffff', text: ''+ImpC.surface2+'', form_bg: '#ffffff', field_bg: ''+ImpC.light+'', field_border: '#cccccc' },
                    field_border_width: 1, field_radius: 10, button_radius: 10
                },
                minimal: {
                    colors: { button: '#000000', button_text: '#ffffff', text: '#000000', form_bg: '#ffffff', field_bg: '#ffffff', field_border: ''+ImpC.text+'' },
                    field_border_width: 1, field_radius: 4, button_radius: 4
                },
                classic: {
                    colors: { button: '#444444', button_text: '#ffffff', text: '#333333', form_bg: ''+ImpC.light+'', field_bg: '#ffffff', field_border: '#cccccc' },
                    field_border_width: 1, field_radius: 6, button_radius: 6
                },
                bold: {
                    colors: { button: '#000000', button_text: '#ffffff', text: '#000000', form_bg: '#ffffff', field_bg: '#f0f0f0', field_border: '#000000' },
                    field_border_width: 2, field_radius: 0, button_radius: 0
                }
            };
            
            function updateColor(name, value) {
                var $row = $('[data-name="' + name + '"]');
                $row.find('input[name="' + name + '"]').val(value);
                $row.find('.impulse-color-swatch').css('--swatch-color', value);
            }
            
            if (presets[preset]) {
                var p = presets[preset];
                updateColor('checkout_design_button', p.colors.button);
                updateColor('checkout_design_button_text', p.colors.button_text);
                updateColor('checkout_design_text', p.colors.text);
                updateColor('checkout_design_form_bg', p.colors.form_bg);
                updateColor('checkout_design_field_bg', p.colors.field_bg);
                updateColor('checkout_design_field_border', p.colors.field_border);
                
                $('input[name="checkout_design_field_border_width"]').val(p.field_border_width).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(p.field_border_width + 'px');
                $('input[name="checkout_design_field_radius"]').val(p.field_radius).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(p.field_radius + 'px');
                $('input[name="checkout_design_button_radius"]').val(p.button_radius).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(p.button_radius + 'px');
            }
            autoSaveAndPreview(true);
        });

        var checkoutFieldsObserver = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        var $list = $(node).find('.impulse-checkout-fields-list').addBack('.impulse-checkout-fields-list');
                        $list.each(function() {
                            var $el = $(this);
                            if ($el.data('sortable-init')) return;
                            $el.data('sortable-init', true);
                            
                            if (typeof Sortable !== 'undefined') {
                                new Sortable($el[0], {
                                    animation: 150,
                                    ghostClass: 'sortable-ghost',
                                    dragClass: 'sortable-drag',

                                    
                                    filter: 'input, label, .impulse-field-required-toggle',
                                    preventOnFilter: false,
                                    onEnd: function() {
                                        updateCheckoutFieldsJSON();
                                        autoSaveAndRefresh();
                                    }
                                });
                            }
                        });
                    }
                });
            });
        });
        checkoutFieldsObserver.observe(document.body, { childList: true, subtree: true });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.impulse-field-popover, .impulse-field-settings-btn').length) {
                $('.impulse-checkout-field-item, .impulse-form-field-item').removeClass('popover-active');
                $('.impulse-field-popover').remove();
            }
        });

        $(document).on('click', '.impulse-field-settings-btn', function(e) {
            e.stopPropagation();
            var $btn = $(this);
            var $item = $btn.closest('.impulse-checkout-field-item, .impulse-form-field-item');
            var isCheckoutField = $item.hasClass('impulse-checkout-field-item');
            var isFormField = $item.hasClass('impulse-form-field-item');

            var device = window.impulseDevice || 'desktop';
            var suffix = device === 'desktop' ? '' : '-' + device;

            $('.impulse-checkout-field-item, .impulse-form-field-item').removeClass('popover-active');
            $('.impulse-field-popover').remove();

            $item.addClass('popover-active');
            
            if (isCheckoutField) {
                
                var fieldId = $item.data('field-id');
                var isAddress = $item.data('address') === 1;
                var isEmail = $item.data('email') === 1;

                var isRequired, isEnabled, width;
                if (device === 'desktop') {
                    isRequired = $item.data('required') === 1;
                    isEnabled = $item.data('enabled') === 1;
                    width = $item.data('width') || 'full';
                } else {
                    isRequired = $item.data('required' + suffix) === 1;
                    isEnabled = $item.data('enabled' + suffix) === 1;
                    width = $item.data('width' + suffix) || (device === 'mobile' ? 'full' : ($item.data('width') || 'full'));
                }

                var html = '<div class="impulse-field-popover" data-device="' + device + '" data-field-type="checkout">';
                
                html += '<div class="impulse-field-popover-row' + (isEmail ? ' locked' : '') + '" data-action="required">';
                html += '<span>Required</span>';
                if (isEmail) {
                    html += '<div class="impulse-field-popover-toggle active disabled"></div>';
                } else {
                    html += '<div class="impulse-field-popover-toggle' + (isRequired ? ' active' : '') + '"></div>';
                }
                html += '</div>';
                
                html += '<div class="impulse-field-popover-row' + (isEmail ? ' locked' : '') + '" data-action="visible">';
                html += '<span>Visible</span>';
                if (isEmail) {
                    html += '<div class="impulse-field-popover-toggle active disabled"></div>';
                } else {
                    html += '<div class="impulse-field-popover-toggle' + (isEnabled ? ' active' : '') + '"></div>';
                }
                html += '</div>';
                if (!isAddress) {
                    html += '<div class="impulse-field-popover-row" data-action="width">';
                    html += '<span>Half Width</span>';
                    html += '<div class="impulse-field-popover-toggle' + (width === 'half' ? ' active' : '') + '"></div>';
                    html += '</div>';
                }
                
                if (fieldId.indexOf('custom_') === 0) {
                    html += '<div class="impulse-field-popover-divider"></div>';
                    html += '<div class="impulse-field-popover-row" data-action="delete" style="color:'+ImpC.dim+'">';
                    html += '<span>Delete Field</span>';
                    html += '</div>';
                }
                html += '</div>';
                
                $item.append(html);
            } else if (isFormField) {
                
                var fieldType = $item.data('field-type') || 'text';
                var isTextarea = fieldType === 'textarea';

                var isRequired, width;
                if (device === 'desktop') {
                    isRequired = $item.data('required') === 1;
                    width = $item.data('width') || 'full';
                } else {
                    isRequired = $item.data('required' + suffix) === 1;
                    width = $item.data('width' + suffix) || (device === 'mobile' ? 'full' : ($item.data('width') || 'full'));
                }

                var html = '<div class="impulse-field-popover" data-device="' + device + '" data-field-type="contact">';

                html += '<div class="impulse-field-popover-row" data-action="type" style="flex-direction:column;align-items:flex-start;gap:6px">';
                html += '<span style="margin-bottom:2px">Type</span>';
                html += '<select class="impulse-form-field-type-select" style="width:100%;padding:4px 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px">';
                var types = [{v:'text',l:'Text'},{v:'email',l:'Email'},{v:'phone',l:'Phone'},{v:'number',l:'Number'},{v:'date',l:'Date'},{v:'time',l:'Time'},{v:'textarea',l:'Textarea'},{v:'select',l:'Dropdown'},{v:'checkbox',l:'Checkbox'}];
                types.forEach(function(t) {
                    html += '<option value="' + t.v + '"' + (fieldType === t.v ? ' selected' : '') + '>' + t.l + '</option>';
                });
                html += '</select>';
                html += '</div>';

                html += '<div class="impulse-field-popover-row" data-action="required">';
                html += '<span>Required</span>';
                html += '<div class="impulse-field-popover-toggle' + (isRequired ? ' active' : '') + '"></div>';
                html += '</div>';

                if (!isTextarea) {
                    html += '<div class="impulse-field-popover-row" data-action="width">';
                    html += '<span>Half Width</span>';
                    html += '<div class="impulse-field-popover-toggle' + (width === 'half' ? ' active' : '') + '"></div>';
                    html += '</div>';
                }

                html += '<div class="impulse-field-popover-divider"></div>';
                html += '<div class="impulse-field-popover-row" data-action="delete" style="color:'+ImpC.dim+'">';
                html += '<span>Delete Field</span>';
                html += '</div>';
                html += '</div>';
                
                $item.append(html);
            }
        });

        $(document).on('click', '.impulse-field-popover-row', function(e) {
            e.stopPropagation();
            var $row = $(this);

            if ($row.hasClass('locked')) return;
            
            var action = $row.data('action');
            var $popover = $row.closest('.impulse-field-popover');
            var fieldType = $popover.data('field-type'); 
            var $item = $row.closest('.impulse-checkout-field-item, .impulse-form-field-item');
            var $toggle = $row.find('.impulse-field-popover-toggle');

            var device = $popover.data('device') || 'desktop';
            var suffix = device === 'desktop' ? '' : '-' + device;
            var dataKey = function(base) { return device === 'desktop' ? base : base + suffix; };
            
            if (action === 'required') {
                var isActive = $toggle.hasClass('active');
                $toggle.toggleClass('active');
                $item.data(dataKey('required'), isActive ? 0 : 1);
            } else if (action === 'visible') {
                var isActive = $toggle.hasClass('active');
                $toggle.toggleClass('active');
                var newEnabled = !isActive;
                $item.data(dataKey('enabled'), newEnabled ? 1 : 0);

                if (device === 'desktop') {
                    $item.toggleClass('disabled', !newEnabled);
                }

                if (!newEnabled) {
                    $item.data(dataKey('required'), 0);
                    $row.siblings('[data-action="required"]').find('.impulse-field-popover-toggle').removeClass('active');
                }

                if (fieldType === 'checkout') {
                    var fieldId = $item.data('field-id');
                    if (fieldId === 'address_1' && !newEnabled) {
                        var $addr2 = $('.impulse-checkout-field-item[data-field-id="address_2"]');
                        $addr2.data(dataKey('enabled'), 0).data(dataKey('required'), 0);
                        if (device === 'desktop') {
                            $addr2.addClass('disabled');
                        }
                    }
                }
            } else if (action === 'width') {
                var isActive = $toggle.hasClass('active');
                $toggle.toggleClass('active');
                var newWidth = isActive ? 'full' : 'half';
                $item.data(dataKey('width'), newWidth);
            } else if (action === 'delete') {
                $('.impulse-field-popover').remove();
                $item.remove();
            }

            if (fieldType === 'checkout') {
                updateCheckoutFieldsJSON();
            } else if (fieldType === 'contact') {
                updateFormFieldsJSON();
            }
            autoSaveAndRefresh();
        });

        $(document).on('change', '.impulse-form-field-type-select', function() {
            var $select = $(this);
            var $item = $select.closest('.impulse-form-field-item');
            var newType = $select.val();
            $item.data('field-type', newType);
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });

        $(document).on('change', '.impulse-checkout-field-label', function() {
            updateCheckoutFieldsJSON();
            autoSaveAndRefresh();
        });

        $(document).on('change', '.impulse-checkout-field-item .impulse-field-required-cb', function() {
            updateCheckoutFieldsJSON();
            autoSaveAndRefresh();
        });

        $(document).on('click', '#impulse-add-checkout-field', function() {
            var $list = $('.impulse-checkout-fields-list');
            var idx = $list.find('.impulse-checkout-field-item').length;
            var fieldId = 'custom_' + Date.now();
            
            var html = '<div class="impulse-checkout-field-item" data-field-id="' + fieldId + '" data-index="' + idx + '" data-width="full" data-required="0" data-enabled="1" draggable="true">';
            html += '<input type="text" class="impulse-checkout-field-label" value="Custom Field">';
            html += '<label class="impulse-field-required-toggle" title="Required">';
            html += '<input type="checkbox" class="impulse-field-required-cb">';
            html += '</label>';
            html += '</div>';
            
            $list.append(html);
            updateCheckoutFieldsJSON();
            autoSaveAndRefresh();
        });

        function updateCheckoutFieldsJSON() {
            var _halfCk = {email:1, phone:1, first_name:1, last_name:1, city:1, state:1, postcode:1, country:1};
            var fields = [];
            $('.impulse-checkout-fields-list .impulse-checkout-field-item').each(function() {
                var $item = $(this);
                var id = $item.data('field-id');
                var label = $item.find('.impulse-checkout-field-label').val();
                var locked = id === 'email';
                var required = $item.find('.impulse-field-required-cb').is(':checked') || locked;
                var width = _halfCk[id] ? 'half' : 'full';
                fields.push({ id: id, label: label, enabled: true, required: required, width: width, locked: locked });
            });
            $('input[name="checkout_design_fields"]').val(JSON.stringify(fields));
        }

        

        
        function updateFormFieldsJSON() {
            var fields = [];
            $('.impulse-form-fields-list .impulse-form-field-item').each(function() {
                var $item = $(this);
                var type = $item.find('.impulse-form-field-type-select').val() || $item.data('field-type') || 'text';
                var label = $item.find('.impulse-form-field-label').val();
                var name = $item.data('name') || (label || '').toLowerCase().replace(/[^a-z0-9]/g, '_');
                var required = $item.find('.impulse-field-required-cb').is(':checked');
                var width = $item.attr('data-width') || 'full';
                var placeholder = $item.attr('data-placeholder') || '';

                var $opts = $item.find('.impulse-form-field-options');
                var options = $opts.length ? $opts.val() : ($item.attr('data-options') || '');
                var f = { type: type, label: label, name: name, placeholder: placeholder, required: required, width: width };
                if (type === 'select') f.options = options;
                fields.push(f);
            });
            $('input[name="fields"]').val(JSON.stringify(fields));
        }

        $(document).on('click', '.impulse-form-field-delete', function(e) {
            e.preventDefault(); e.stopPropagation();
            $(this).closest('.impulse-form-field-item').remove();
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });
        
        $(document).on('change', '.impulse-form-field-item .impulse-form-field-type-select', function() {
            var $item = $(this).closest('.impulse-form-field-item');
            var newType = $(this).val();
            $item.attr('data-field-type', newType);

            
            $item.find('.impulse-form-field-options').css('display', newType === 'select' ? 'block' : 'none');
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });
        
        $(document).on('input', '.impulse-form-field-item .impulse-form-field-options', function() {
            var $item = $(this).closest('.impulse-form-field-item');
            $item.attr('data-options', $(this).val());
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });

        
        function _impFieldCbRepaint($sq, on) {
            $sq.css({
                background: on ? '#ffffff' : 'transparent',
                'border-color': on ? '#ffffff' : '#555'
            });
        }
        $(document).on('change', '.impulse-form-field-item .impulse-field-half-cb', function() {
            var $item = $(this).closest('.impulse-form-field-item');
            var on = $(this).is(':checked');
            $item.attr('data-width', on ? '50' : '100');
            _impFieldCbRepaint($(this).closest('.impulse-field-width-toggle').find('.impulse-field-cb-square'), on);
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('change', '.impulse-form-field-item .impulse-field-required-cb', function() {
            var on = $(this).is(':checked');
            _impFieldCbRepaint($(this).closest('.impulse-field-required-toggle').find('.impulse-field-cb-square'), on);
        });
        $(document).on('change', '.impulse-form-field-item .impulse-field-required-cb', function() {
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('change', '.impulse-form-field-item .impulse-form-field-label', function() {
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });

        var _netInp = 'padding:0 6px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;box-sizing:border-box';

        function netUniqueId() {
            var used = {};
            $('.impulse-net-cards-list .net-card-id').each(function () { var v = ($(this).val() || '').trim(); if (v) used[v] = 1; });
            var i = 1; while (used['c' + i]) i++;
            return 'c' + i;
        }
        function impulseNetCardRow(c) {
            c = c || {};
            var icon = c.icon || 'circle';
            var _col = (c.col != null ? c.col : 0), _row = (c.row != null ? c.row : 0);
            var h = '<div class="impulse-net-card-item" data-col="' + _col + '" data-row="' + _row + '" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;padding:5px;background:' + ImpC.surface + ';border:1px solid ' + ImpC.border + ';border-radius:4px">';
            h += '<button type="button" class="impulse-net-icon-btn" data-icon="' + escapeHtml(icon) + '" title="Choose icon" style="width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';cursor:pointer;flex-shrink:0">' + (lucideSvg(icon, 16) || '') + '</button>';

            h += '<input type="hidden" class="net-card-id" value="' + escapeHtml(c.id || '') + '">';
            h += '<input type="text" class="net-card-label" value="' + escapeHtml(c.label || '') + '" placeholder="Label" title="Card name, shown on the card and used in routes" style="flex:1;min-width:0;height:24px;' + _netInp + '">';
            h += '<button type="button" class="impulse-net-card-remove" title="Remove card" style="width:24px;height:24px;background:transparent;border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.muted + ';cursor:pointer;font-size:15px;line-height:1;flex-shrink:0">&times;</button>';
            h += '<textarea class="net-card-desc" placeholder="Description (shown on hover / in modal)" rows="2" style="flex:0 0 100%;min-height:46px;padding:6px 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;box-sizing:border-box;resize:vertical;font-family:inherit;line-height:1.4">' + escapeHtml(c.desc || '') + '</textarea>';
            h += '<input type="text" class="net-card-link" value="' + escapeHtml(c.link || '') + '" placeholder="Link (optional)" style="flex:0 0 100%;height:24px;' + _netInp + '">';
            h += '</div>';
            return h;
        }
        function netRouteChip(id, label) {
            return '<span class="net-route-chip" data-id="' + escapeHtml(id) + '" title="Drag to reorder" style="display:inline-flex;align-items:center;gap:3px;padding:2px 3px 2px 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:12px;font-size:11px;color:' + ImpC.text + ';cursor:grab;touch-action:none">' + escapeHtml(label || id) + '<button type="button" class="net-route-chip-x" title="Remove" style="border:none;background:transparent;color:' + ImpC.muted + ';cursor:pointer;font-size:13px;line-height:1;padding:0 2px">&times;</button></span>';
        }
        function currentNetCards() {
            var cards = [];
            $('.impulse-net-cards-list .impulse-net-card-item').each(function(i) {
                cards.push({ id: ($(this).find('.net-card-id').val() || ('c' + (i + 1))).trim(), label: $(this).find('.net-card-label').val() || '' });
            });
            return cards;
        }

        
        function netLineRow(ids, cards, labelOf) {
            ids = ids || [];
            var h = '<div class="impulse-net-line" style="display:flex;flex-direction:column;gap:4px;width:100%">';
            h += '<div class="impulse-net-route-chips" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;width:100%;min-width:0">';
            ids.forEach(function(id) { h += netRouteChip(id, labelOf[id]); });
            h += '</div>';
            h += '<div style="display:flex;gap:4px;align-items:center">';
            h += '<select class="net-route-add" title="Add a card to this line" style="height:24px;flex:0 0 auto;max-width:130px;' + _netInp + '"><option value="">+ Card</option>';
            cards.forEach(function(c) { h += '<option value="' + escapeHtml(c.id) + '">' + escapeHtml(c.label || c.id) + '</option>'; });
            h += '</select>';
            h += '<button type="button" class="impulse-net-line-remove" title="Remove this line" style="width:22px;height:22px;flex:0 0 auto;background:transparent;border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.muted + ';cursor:pointer;font-size:14px;line-height:1">&times;</button>';
            h += '</div>';
            h += '</div>';
            return h;
        }
        function impulseNetRouteRow(r, cards) {
            cards = cards || [];
            var labelOf = {};
            cards.forEach(function(c) { labelOf[c.id] = c.label || c.id; });
            
            var lines;
            if (Array.isArray(r) && r.length && Array.isArray(r[0])) lines = r;
            else if (Array.isArray(r)) lines = [r];
            else if (r && r.cards) lines = [r.cards];
            else lines = [[]];
            if (!lines.length) lines = [[]];

            var h = '<div class="impulse-net-route-item" style="display:flex;flex-direction:column;gap:6px;padding:6px;background:' + ImpC.surface + ';border:1px solid ' + ImpC.border + ';border-radius:4px">';
            h += '<div class="impulse-net-lines" style="display:flex;flex-direction:column;gap:8px;width:100%">';
            lines.forEach(function(line) { h += netLineRow(line, cards, labelOf); });
            h += '</div>';
            h += '<div style="display:flex;justify-content:space-between;align-items:center;gap:6px">';
            h += '<button type="button" class="impulse-net-add-line" title="Add a parallel line that fires together with this route" style="height:22px;padding:0 8px;background:transparent;border:1px dashed ' + ImpC.border + ';border-radius:3px;color:' + ImpC.muted + ';cursor:pointer;font-size:10px">+ Parallel line</button>';
            h += '<button type="button" class="impulse-net-route-remove" title="Remove this route" style="height:22px;padding:0 8px;background:transparent;border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.muted + ';cursor:pointer;font-size:10px">Remove</button>';
            h += '</div>';
            h += '</div>';
            return h;
        }
        function updateNetCardsJSON() {
            var cards = [];
            $('.impulse-net-cards-list .impulse-net-card-item').each(function(i) {
                var $i = $(this);
                var id = ($i.find('.net-card-id').val() || '').trim() || ('c' + (i + 1));
                cards.push({
                    id: id,
                    icon: ($i.find('.impulse-net-icon-btn').attr('data-icon') || 'circle'),
                    label: $i.find('.net-card-label').val() || '',
                    desc: $i.find('.net-card-desc').val() || '',
                    link: $i.find('.net-card-link').val() || '',
                    col: parseInt($i.attr('data-col'), 10) || 0,
                    row: parseInt($i.attr('data-row'), 10) || 0
                });
            });
            $('input[name="cards"]').val(JSON.stringify(cards));
        }
        function updateNetRoutesJSON() {
            var routes = [];
            $('.impulse-net-routes-list .impulse-net-route-item').each(function() {
                var lines = [];
                $(this).find('.impulse-net-line').each(function() {
                    var ids = [];
                    $(this).find('.net-route-chip').each(function() { var id = $(this).attr('data-id'); if (id) ids.push(id); });
                    if (ids.length >= 2) lines.push(ids);
                });
                if (lines.length === 1) routes.push(lines[0]);   
                else if (lines.length > 1) routes.push(lines);   
            });

            $('.impulse-net-routes-input').val(JSON.stringify(routes));
        }
        $(document).on('click', '.impulse-net-icon-btn', function() {
            if (typeof loadIcons === 'function') loadIcons();
            $('#impulse-icon-modal').data('target', 'net_card').data('net-card-btn', $(this)).show();
        });
        $(document).on('change', '.impulse-net-card-item input, .impulse-net-card-item textarea', function() {
            updateNetCardsJSON();
            refreshRouteDropdowns();
            autoSaveAndRefresh();
        });
        $(document).on('click', '#impulse-add-net-card', function() {
            var ncols = parseInt($('.impulse-panel-right input[name="cols"]').val(), 10) || 4;
            var n = $('.impulse-net-cards-list .impulse-net-card-item').length;
            $('.impulse-net-cards-list').append(impulseNetCardRow({ id: netUniqueId(), icon: 'circle', label: 'Card', desc: '', link: '', col: n % ncols, row: Math.floor(n / ncols) }));
            updateNetCardsJSON();
            refreshRouteDropdowns();
            autoSaveAndRefresh();
        });

        function impulseMarqueeCardsMatchMode(cards, mode) {
            if (!Array.isArray(cards) || !cards.length) return false;
            var c = cards[0] || {};
            if (mode === 'testimonial') return ('quote' in c) || ('rating' in c) || ('name' in c);
            if (mode === 'image') return ('image' in c) || ('image_id' in c) || ('caption' in c);
            return ('icon' in c);
        }
        function impulseMarqueeStarterCards(mode) {
            if (mode === 'image') {
                return [{ image: '', caption: '', link: '', row: 0 }, { image: '', caption: '', link: '', row: 0 }, { image: '', caption: '', link: '', row: 0 }, { image: '', caption: '', link: '', row: 0 }];
            }
            if (mode === 'testimonial') {
                return [
                    { name: 'Sarah M.', role: 'Homeowner', rating: 5, quote: 'On time, tidy, and the result looks fantastic. Could not be happier.', avatar: '', row: 0 },
                    { name: 'James K.', role: 'Local business', rating: 5, quote: 'Booked online in two minutes and got a confirmation text right away.', avatar: '', row: 0 },
                    { name: 'Emily R.', role: 'Repeat customer', rating: 5, quote: 'Second time using them. Same great service, fair price, no surprises.', avatar: '', row: 0 }
                ];
            }
            return [
                { icon: 'search', title: 'Found on Google', subtitle: 'Built-in SEO', link: '', new_tab: false, row: 0 },
                { icon: 'shopping-bag', title: 'Storefront', subtitle: 'Sell online', link: '', new_tab: false, row: 0 },
                { icon: 'clipboard-list', title: 'Live menus', subtitle: 'Update everywhere', link: '', new_tab: false, row: 0 },
                { icon: 'credit-card', title: 'Payments', subtitle: 'Cards and wallets', link: '', new_tab: false, row: 0 },
                { icon: 'calendar', title: 'Bookings', subtitle: 'Schedule and pay', link: '', new_tab: false, row: 1 },
                { icon: 'message-circle', title: 'Smart chat', subtitle: 'SMS and WhatsApp', link: '', new_tab: false, row: 1 },
                { icon: 'star', title: 'Reviews', subtitle: 'Social proof', link: '', new_tab: false, row: 1 },
                { icon: 'database', title: 'Your data', subtitle: 'All in one place', link: '', new_tab: false, row: 1 }
            ];
        }
        function impulseMarqueeThumbBtn(kind, url) {
            var inner = url ? '<img src="' + escapeHtml(url) + '" style="width:100%;height:100%;object-fit:cover;border-radius:2px">' : '<span style="font-size:16px;color:' + ImpC.muted + '">+</span>';
            return '<button type="button" class="impulse-mq-img-btn" data-kind="' + kind + '" title="Choose ' + (kind === 'avatar' ? 'photo' : 'image') + '" style="width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;overflow:hidden;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;cursor:pointer;flex-shrink:0;padding:0">' + inner + '</button>';
        }
        function impulseMarqueeCardRow(c, mode) {
            c = c || {};
            mode = mode || ($('input[name="mode"]').val() || 'icon');
            var row = (c.row != null ? c.row : 0);
            var _mqInp = 'padding:0 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;box-sizing:border-box';
            var rowSel = '<select class="mq-card-row" title="Which row" style="flex:0 0 auto;height:24px;' + _mqInp + '">';
            ['Row 1', 'Row 2', 'Row 3'].forEach(function (lbl, ri) { rowSel += '<option value="' + ri + '"' + (row === ri ? ' selected' : '') + '>' + lbl + '</option>'; });
            rowSel += '</select>';
            var removeBtn = '<button type="button" class="impulse-mq-card-remove" title="Remove card" style="width:24px;height:24px;background:transparent;border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.muted + ';cursor:pointer;font-size:15px;line-height:1;flex-shrink:0">&times;</button>';
            var linkRow = '<div style="flex:0 0 100%;display:flex;gap:4px;align-items:center"><input type="text" class="mq-card-link" value="' + escapeHtml(c.link || '') + '" placeholder="Link (optional)" style="flex:1;min-width:0;height:24px;' + _mqInp + '"><label style="flex:0 0 auto;display:flex;align-items:center;gap:4px;font-size:10px;color:' + ImpC.muted + ';cursor:pointer" title="Open link in a new tab"><input type="checkbox" class="mq-card-newtab"' + (c.new_tab ? ' checked' : '') + ' style="margin:0;width:13px;height:13px"> New tab</label></div>';
            var h = '<div class="impulse-mq-card-item" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;padding:5px;background:' + ImpC.surface + ';border:1px solid ' + ImpC.border + ';border-radius:4px">';
            if (mode === 'image') {
                h += impulseMarqueeThumbBtn('image', c.image || '');
                h += '<input type="text" class="mq-card-caption" value="' + escapeHtml(c.caption || '') + '" placeholder="Caption (optional)" style="flex:1;min-width:0;height:24px;' + _mqInp + '">';
                h += rowSel + removeBtn;
                h += '<input type="hidden" class="mq-card-image" value="' + escapeHtml(c.image || '') + '">';
                h += '<input type="hidden" class="mq-card-image-id" value="' + escapeHtml(String(c.image_id || '')) + '">';
                h += linkRow;
            } else if (mode === 'testimonial') {
                h += impulseMarqueeThumbBtn('avatar', c.avatar || '');
                h += '<input type="text" class="mq-card-name" value="' + escapeHtml(c.name || '') + '" placeholder="Name" style="flex:1;min-width:0;height:24px;' + _mqInp + '">';
                h += rowSel + removeBtn;
                h += '<input type="hidden" class="mq-card-avatar" value="' + escapeHtml(c.avatar || '') + '">';
                h += '<input type="hidden" class="mq-card-avatar-id" value="' + escapeHtml(String(c.avatar_id || '')) + '">';
                h += '<input type="text" class="mq-card-role" value="' + escapeHtml(c.role || '') + '" placeholder="Role / company (optional)" style="flex:1;min-width:0;height:24px;' + _mqInp + '">';
                var rating = (c.rating != null ? parseInt(c.rating, 10) : 5);
                h += '<select class="mq-card-rating" title="Star rating" style="flex:0 0 auto;height:24px;' + _mqInp + '">';
                [5, 4, 3, 2, 1, 0].forEach(function (rv) { h += '<option value="' + rv + '"' + (rating === rv ? ' selected' : '') + '>' + (rv ? rv + ' stars' : 'No stars') + '</option>'; });
                h += '</select>';
                h += '<textarea class="mq-card-quote" placeholder="Quote" rows="2" style="flex:0 0 100%;' + _mqInp + ';height:auto;padding:6px 8px;resize:vertical;font-family:inherit">' + escapeHtml(c.quote || '') + '</textarea>';
            } else {
                var icon = c.icon || 'star';
                h += '<button type="button" class="impulse-mq-icon-btn" data-icon="' + escapeHtml(icon) + '" title="Choose icon" style="width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';cursor:pointer;flex-shrink:0">' + (lucideSvg(icon, 16) || '') + '</button>';
                h += '<input type="text" class="mq-card-title" value="' + escapeHtml(c.title || '') + '" placeholder="Title" style="flex:1;min-width:0;height:24px;' + _mqInp + '">';
                h += rowSel + removeBtn;
                h += '<input type="text" class="mq-card-sub" value="' + escapeHtml(c.subtitle || '') + '" placeholder="Subtitle" style="flex:0 0 100%;height:24px;' + _mqInp + '">';
                h += linkRow;
                h += '<input type="text" class="mq-card-back" value="' + escapeHtml(c.back || '') + '" placeholder="Hover detail (optional)" style="flex:0 0 100%;height:24px;' + _mqInp + '">';
            }
            h += '</div>';
            return h;
        }
        function updateMarqueeCardsJSON() {
            var mode = $('input[name="mode"]').val() || 'icon';
            var cards = [];
            $('.impulse-mq-cards-list .impulse-mq-card-item').each(function () {
                var $i = $(this);
                var card = { row: parseInt($i.find('.mq-card-row').val(), 10) || 0 };
                if (mode === 'image') {
                    card.image = $i.find('.mq-card-image').val() || '';
                    card.image_id = parseInt($i.find('.mq-card-image-id').val(), 10) || 0;
                    card.caption = $i.find('.mq-card-caption').val() || '';
                    card.link = $i.find('.mq-card-link').val() || '';
                    card.new_tab = $i.find('.mq-card-newtab').is(':checked');
                } else if (mode === 'testimonial') {
                    card.avatar = $i.find('.mq-card-avatar').val() || '';
                    card.avatar_id = parseInt($i.find('.mq-card-avatar-id').val(), 10) || 0;
                    card.name = $i.find('.mq-card-name').val() || '';
                    card.role = $i.find('.mq-card-role').val() || '';
                    var rt = parseInt($i.find('.mq-card-rating').val(), 10);
                    card.rating = isNaN(rt) ? 5 : rt;
                    card.quote = $i.find('.mq-card-quote').val() || '';
                } else {
                    card.icon = $i.find('.impulse-mq-icon-btn').attr('data-icon') || 'star';
                    card.title = $i.find('.mq-card-title').val() || '';
                    card.subtitle = $i.find('.mq-card-sub').val() || '';
                    card.back = $i.find('.mq-card-back').val() || '';
                    card.link = $i.find('.mq-card-link').val() || '';
                    card.new_tab = $i.find('.mq-card-newtab').is(':checked');
                }
                cards.push(card);
            });
            $('input[name="cards"]').val(JSON.stringify(cards));
        }
        $(document).on('click', '.impulse-mq-icon-btn', function () {
            if (typeof loadIcons === 'function') loadIcons();
            $('#impulse-icon-modal').data('target', 'mq_card').data('mq-card-btn', $(this)).show();
        });
        $(document).on('change', '.impulse-mq-card-item input, .impulse-mq-card-item select, .impulse-mq-card-item textarea', function () {
            updateMarqueeCardsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.impulse-mq-img-btn', function () {
            var $btn = $(this);
            var kind = $btn.attr('data-kind') || 'image';
            if (typeof openImglibPicker !== 'function') return;
            openImglibPicker({ label: kind === 'avatar' ? 'Choose photo' : 'Choose image' }, function (attachment) {
                if (!attachment || !attachment.url) return;
                var $item = $btn.closest('.impulse-mq-card-item');
                $item.find('.mq-card-' + kind).val(attachment.url);
                $item.find('.mq-card-' + kind + '-id').val(attachment.id || '');
                $btn.html('<img src="' + escapeHtml(attachment.url) + '" style="width:100%;height:100%;object-fit:cover;border-radius:2px">');
                updateMarqueeCardsJSON();
                autoSaveAndRefresh();
            });
        });
        $(document).on('click', '#impulse-add-mq-card', function () {
            var mode = $('input[name="mode"]').val() || 'icon';
            var starter = mode === 'image' ? { image: '', caption: '', link: '', row: 0 }
                : mode === 'testimonial' ? { name: 'New review', role: '', rating: 5, quote: '', avatar: '', row: 0 }
                : { icon: 'star', title: 'New card', subtitle: '', link: '', new_tab: false, row: 0 };
            $('.impulse-mq-cards-list').append(impulseMarqueeCardRow(starter, mode));
            updateMarqueeCardsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.impulse-mq-card-remove', function () {
            $(this).closest('.impulse-mq-card-item').remove();
            updateMarqueeCardsJSON();
            autoSaveAndRefresh();
        });

        

        $(document).on('click', '.impulse-btn-group[data-name="cols"] button, .impulse-btn-group[data-name="rows"] button', function() {

            
            if ((window.impulseDevice || 'desktop') !== 'desktop') return;
            var $cards = $('.impulse-net-cards-list .impulse-net-card-item');
            if (!$cards.length) return;
            var ncols = parseInt($('.impulse-panel-right input[name="cols"]').val(), 10) || 4;
            if (ncols < 1) ncols = 1;
            $cards.each(function(i) {
                $(this).attr('data-col', i % ncols).attr('data-row', Math.floor(i / ncols));
            });
            if (typeof updateNetCardsJSON === 'function') updateNetCardsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.impulse-net-card-remove', function() {
            $(this).closest('.impulse-net-card-item').remove();
            updateNetCardsJSON();
            refreshRouteDropdowns();
            autoSaveAndRefresh();
        });

        

        
        var _rvAvatarIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="' + ImpC.muted + '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6.5 8-6.5s8 2.5 8 6.5"/></svg>';
        function impulseReviewRow(r) {
            r = r || {};
            var _baseInp = 'height:24px;padding:0 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;box-sizing:border-box';

            var rating = (r.rating != null ? parseInt(r.rating, 10) : 5);
            if (rating !== 4) rating = 5;
            var av = (r.avatar || '').trim();
            var h = '<div class="impulse-review-item" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;padding:6px;background:' + ImpC.surface + ';border:1px solid ' + ImpC.border + ';border-radius:4px">';

            h += '<span class="rv-avatar-wrap" style="position:relative;flex:0 0 auto;display:inline-flex">';
            h += '<button type="button" class="rv-avatar-btn" title="Reviewer photo (optional)" style="width:28px;height:28px;border-radius:50%;border:1px solid ' + ImpC.border + ';background-color:' + ImpC.panel + ';background-size:cover;background-position:center;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;overflow:hidden;padding:0' + (av ? (';background-image:url(\'' + escapeHtml(av) + '\')') : '') + '">' + (av ? '' : _rvAvatarIcon) + '</button>';
            h += '<button type="button" class="rv-avatar-clear" title="Remove photo" style="position:absolute;top:-5px;right:-5px;width:15px;height:15px;border-radius:50%;border:none;background:' + ImpC.muted + ';color:#fff;font-size:11px;line-height:1;cursor:pointer;padding:0;align-items:center;justify-content:center;display:' + (av ? 'flex' : 'none') + '">&times;</button>';
            h += '<input type="hidden" class="rv-avatar" value="' + escapeHtml(av) + '">';
            h += '</span>';
            h += '<input type="text" class="rv-name" value="' + escapeHtml(r.name || '') + '" placeholder="Reviewer name" style="flex:1;min-width:0;' + _baseInp + '">';
            h += '<select class="rv-rating" title="Star rating" style="width:56px;flex:0 0 auto;' + _baseInp + '">';
            [5, 4].forEach(function (s) { h += '<option value="' + s + '"' + (rating === s ? ' selected' : '') + '>' + s + '★</option>'; });
            h += '</select>';
            h += '<button type="button" class="impulse-review-remove" title="Remove review" style="width:24px;height:24px;flex:0 0 auto;background:transparent;border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.muted + ';cursor:pointer;font-size:15px;line-height:1">&times;</button>';
            h += '<input type="text" class="rv-date" value="' + escapeHtml(r.date || '') + '" placeholder="Date, e.g. 2 weeks ago" style="flex:0 0 100%;' + _baseInp + '">';
            h += '<textarea class="rv-text" placeholder="Review text" rows="2" style="flex:0 0 100%;min-height:46px;padding:6px 8px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;color:' + ImpC.text + ';font-size:11px;box-sizing:border-box;resize:vertical;font-family:inherit;line-height:1.4">' + escapeHtml(r.text || '') + '</textarea>';
            h += '<input type="text" class="rv-url" value="' + escapeHtml(r.url || '') + '" placeholder="Link to this review (optional)" style="flex:0 0 100%;' + _baseInp + '">';
            h += '</div>';
            return h;
        }
        function updateReviewsJSON() {
            var list = [];
            $('.impulse-reviews-list .impulse-review-item').each(function() {
                var $i = $(this);
                var name = ($i.find('.rv-name').val() || '').trim();
                var text = ($i.find('.rv-text').val() || '').trim();
                if (!name && !text) return; 
                list.push({
                    name: name,
                    rating: parseInt($i.find('.rv-rating').val(), 10) || 5,
                    date: ($i.find('.rv-date').val() || '').trim(),
                    text: text,
                    url: ($i.find('.rv-url').val() || '').trim(),
                    avatar: ($i.find('.rv-avatar').val() || '').trim()
                });
            });
            $('input[name="reviews"]').val(JSON.stringify(list));
            return list;
        }
        $(document).on('change', '.impulse-review-item input, .impulse-review-item textarea, .impulse-review-item select', function() {
            updateReviewsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('click', '#impulse-add-review', function() {
            $('.impulse-reviews-list').append(impulseReviewRow({ rating: 5 }));
            updateReviewsJSON();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.impulse-review-remove', function() {
            $(this).closest('.impulse-review-item').remove();
            updateReviewsJSON();
            autoSaveAndRefresh();
        });
        
        $(document).on('click', '.rv-avatar-btn', function() {
            if (typeof openImglibPicker !== 'function') return;
            var $wrap = $(this).closest('.rv-avatar-wrap');
            openImglibPicker({ label: 'Select reviewer photo' }, function(att) {
                var url = (att && att.url) || '';
                if (!url) return;
                $wrap.find('.rv-avatar').val(url);
                $wrap.find('.rv-avatar-btn').css('background-image', 'url(\'' + url + '\')').empty();
                $wrap.find('.rv-avatar-clear').css('display', 'flex');
                updateReviewsJSON();
                autoSaveAndRefresh();
            });
        });
        $(document).on('click', '.rv-avatar-clear', function(e) {
            e.stopPropagation();
            var $wrap = $(this).closest('.rv-avatar-wrap');
            $wrap.find('.rv-avatar').val('');
            $wrap.find('.rv-avatar-btn').css('background-image', '').html(_rvAvatarIcon);
            $(this).css('display', 'none');
            updateReviewsJSON();
            autoSaveAndRefresh();
        });

        
        
        function refreshRouteDropdowns() {
            var cards = currentNetCards();
            $('.net-route-add').each(function() {
                var html = '<option value="">+ Card</option>';
                cards.forEach(function(c) { html += '<option value="' + escapeHtml(c.id) + '">' + escapeHtml(c.label || c.id) + '</option>'; });
                $(this).html(html).val('');
            });
        }
        $(document).on('change', '.net-route-add', function() {
            var id = $(this).val(); if (!id) return;
            var label = $(this).find('option:selected').text();
            $(this).closest('.impulse-net-line').find('.impulse-net-route-chips').append(netRouteChip(id, label));
            this.blur();
            updateNetRoutesJSON();

            
            refreshRouteDropdowns();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.net-route-chip-x', function() {
            $(this).closest('.net-route-chip').remove();
            updateNetRoutesJSON();
            autoSaveAndRefresh();
        });
        
        $(document).on('click', '.impulse-net-add-line', function() {
            $(this).closest('.impulse-net-route-item').find('.impulse-net-lines').append(netLineRow([], currentNetCards(), {}));
            refreshRouteDropdowns();
            updateNetRoutesJSON();
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-net-line-remove', function() {
            var $line = $(this).closest('.impulse-net-line');
            var $route = $line.closest('.impulse-net-route-item');
            if ($route.find('.impulse-net-line').length > 1) $line.remove();
            else $line.find('.impulse-net-route-chips').empty();
            updateNetRoutesJSON();
            autoSaveAndRefresh();
        });

        
        $(document).on('pointerdown', '.net-route-chip', function(ev) {
            if (ev.button != null && ev.button !== 0) return;
            if (ev.target && ev.target.closest && ev.target.closest('.net-route-chip-x')) return;
            var chip = this, box = chip.parentNode, pid = ev.pointerId;
            var startX = ev.clientX, startY = ev.clientY, moved = false;
            try { chip.setPointerCapture(pid); } catch (e) {}
            function onMove(e2) {
                if (!moved && Math.abs(e2.clientX - startX) < 4 && Math.abs(e2.clientY - startY) < 4) return;
                moved = true; chip.style.opacity = '0.55';
                var sibs = box.querySelectorAll('.net-route-chip'), before = null;
                for (var i = 0; i < sibs.length; i++) {
                    if (sibs[i] === chip) continue;
                    var r = sibs[i].getBoundingClientRect();

                    
                    if (e2.clientY < r.top || (e2.clientY <= r.bottom && e2.clientX < r.left + r.width / 2)) { before = sibs[i]; break; }
                }
                if (before) box.insertBefore(chip, before); else box.appendChild(chip);
            }
            function onUp() {
                chip.removeEventListener('pointermove', onMove);
                chip.removeEventListener('pointerup', onUp);
                chip.removeEventListener('pointercancel', onUp);
                try { chip.releasePointerCapture(pid); } catch (e) {}
                chip.style.opacity = '';
                if (moved) { updateNetRoutesJSON(); autoSaveAndRefresh(); }
            }
            chip.addEventListener('pointermove', onMove);
            chip.addEventListener('pointerup', onUp);
            chip.addEventListener('pointercancel', onUp);
        });
        $(document).on('click', '#impulse-add-net-route', function() {
            $('.impulse-net-routes-list').append(impulseNetRouteRow([], currentNetCards()));
            updateNetRoutesJSON();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.impulse-net-route-remove', function() {
            $(this).closest('.impulse-net-route-item').remove();
            updateNetRoutesJSON();
            autoSaveAndRefresh();
        });

        
        $(document).on('change', '.impulse-card-element-cb', function() {
            var elements = [];
            $('.impulse-card-element-cb:checked').each(function() {
                elements.push($(this).data('element'));
            });
            $('input[name="card_design_elements"]').val(JSON.stringify(elements));
            autoSaveAndPreview(); 
        });

        
        function collectCardDesignFromPanel() {
            var $panel = $('.impulse-panel-right');
            var design = {
                elements: JSON.parse($panel.find('input[name="card_design_elements"]').val() || '["image","title","price","add_to_cart","sale_badge","featured_badge"]'),
                card: {
                    background: $panel.find('input[name="card_design_card_background"]').val() || '#ffffff',
                    border_color: $panel.find('input[name="card_design_card_border_color"]').val() || ''+ImpC.text+'',
                    border_width: parseInt($panel.find('input[name="card_design_card_border_width"]').val()) || 0,
                    border_radius: (function(){ var v=parseInt($panel.find('input[name="card_design_card_border_radius"]').val()); return !isNaN(v)?v:8; }()),
                    shadow: $panel.find('input[name="card_design_card_shadow"]').val() || ''
                },
                image: {
                    aspect_ratio: 'square'
                },
                title: {
                    font_size: parseInt($panel.find('input[name="card_design_title_font_size"]').val()) || 16,
                    font_weight: $panel.find('input[name="card_design_title_font_weight"]').val() || '600',
                    color: $panel.find('input[name="card_design_title_color"]').val() || ''+ImpC.surface2+''
                },
                price: {
                    font_size: parseInt($panel.find('input[name="card_design_price_font_size"]').val()) || 18,
                    color: $panel.find('input[name="card_design_price_color"]').val() || ''+ImpC.surface2+'',
                    sale_color: $panel.find('input[name="card_design_price_sale_color"]').val() || '#666666'
                },
                add_to_cart: {
                    button_text: $panel.find('input[name="card_design_add_to_cart_button_text"]').val() || 'Add to Cart',
                    bg_color: $panel.find('input[name="card_design_add_to_cart_bg_color"]').val() || ''+ImpC.surface2+'',
                    text_color: $panel.find('input[name="card_design_add_to_cart_text_color"]').val() || '#ffffff',
                    border_radius: (function(){ var v=parseInt($panel.find('input[name="card_design_add_to_cart_border_radius"]').val()); return isNaN(v)?6:v; })()
                },
                sale_badge: {
                    text: $panel.find('input[name="card_design_sale_badge_text"]').val() || 'Sale',
                    bg_color: $panel.find('input[name="card_design_sale_badge_bg_color"]').val() || ''+ImpC.surface2+'',
                    featured_bg_color: $panel.find('input[name="card_design_featured_badge_bg_color"]').val() || ''+ImpC.surface2+'',
                    text_color: $panel.find('input[name="card_design_sale_badge_text_color"]').val() || '#ffffff'
                }
            };
            return design;
        }

        $(document).on('click', '.impulse-unit-toggle button', function() {
            var $toggle = $(this).closest('.impulse-unit-toggle');
            $toggle.find('button').removeClass('active');
            $(this).addClass('active');
            
            var unit = $(this).data('value');
            var $slider = $toggle.closest('.impulse-slider-with-unit').find('input[type="range"]');
            var currentVal = parseInt($slider.val());
            if (unit === 'vh') {
                $slider.attr('max', 100);
                if (currentVal > 100) $slider.val(100);
                $toggle.closest('.impulse-slider-with-unit').find('.impulse-slider-value').text($slider.val() + 'vh');
            } else {
                $slider.attr('max', 900);
                $toggle.closest('.impulse-slider-with-unit').find('.impulse-slider-value').text($slider.val() + 'px');
            }
            autoSaveAndPreview(true);
        });

        $(document).on('input', '.impulse-slider-with-unit input[type="range"]', function() {
            var unit = $(this).closest('.impulse-slider-with-unit').find('.impulse-unit-toggle button.active').data('value') || 'px';
            $(this).closest('.impulse-slider-with-unit').find('.impulse-slider-value').text($(this).val() + unit);
            autoSaveAndPreview();
        });

        

        

        

        

        
        $(document).on('dblclick', '.impulse-slider-row input[type="range"]', function() {
            var $slider = $(this);
            var defaultVal = parseFloat($slider.attr('data-default'));
            if (isNaN(defaultVal)) defaultVal = 0;
            $slider.attr('data-reset-unset', '1');
            $slider.val(defaultVal).trigger('input');
        });

        

        

        

        

        

        var _swLastT = 0, _swLastEl = null, _swAcc = 0, _swChangeTimer = null;
        var _SW_NOTCH = 80; 
        document.addEventListener('wheel', function(e) {
            var el = e.target;
            if (!el || el.tagName !== 'INPUT' || el.type !== 'range') return;
            var now = Date.now();
            var passingThrough = (now - _swLastT < 250) && _swLastEl !== el;
            _swLastT = now;
            if (passingThrough) { _swLastEl = null; return; }
            if (_swLastEl !== el) _swAcc = 0;
            _swLastEl = el;
            e.preventDefault();

            
            if (_swAcc !== 0 && (e.deltaY > 0) !== (_swAcc > 0)) _swAcc = 0;
            _swAcc += e.deltaY;
            var ticks = Math.trunc(_swAcc / _SW_NOTCH);
            
            if (ticks === 0 && Math.abs(_swAcc) >= _SW_NOTCH) ticks = _swAcc > 0 ? 1 : -1;
            if (ticks === 0) return;
            _swAcc -= ticks * _SW_NOTCH;
            var min  = parseFloat(el.min);  if (isNaN(min)) min = 0;
            var max  = parseFloat(el.max);  if (isNaN(max)) max = 100;
            var step = parseFloat(el.step) || 1;

            var span = (max - min) / step;
            var mult = span > 200 ? Math.round(span / 200) : 1;
            var next = parseFloat(el.value || 0) + ticks * step * mult; 
            var dec  = (String(step).split('.')[1] || '').length;
            next = parseFloat(Math.min(max, Math.max(min, next)).toFixed(dec));
            if (next === parseFloat(el.value)) return;
            el.value = next;
            el.dispatchEvent(new Event('input', { bubbles: true }));
            clearTimeout(_swChangeTimer);
            _swChangeTimer = setTimeout(function() {
                el.dispatchEvent(new Event('change', { bubbles: true }));
            }, 400);
        }, { passive: false });

        
        
        $(document).on('input change', '.impulse-slider-row input[type="range"]', function() {

            
            
            var $s = $(this);
            if ($s.attr('data-reset-unset')) {
                setTimeout(function() { $s.removeAttr('data-reset-unset'); }, 0);
            }
        });

        

        
        $(document).on('dblclick', '.impulse-padding-section .impulse-section-divider, .impulse-margins-section .impulse-section-divider', function() {
            var $section = $(this).closest('.impulse-padding-section, .impulse-margins-section');
            $section.find('input[type="range"]').each(function() {
                var $s = $(this);
                var def = parseFloat($s.attr('data-default'));
                if (isNaN(def)) def = 0;
                $s.attr('data-reset-unset', '1');
                $s.val(def).trigger('input');
            });
        });

        
        
        $(document).on('mousedown', '.impulse-slider-value', function(e) {
            if (e.button !== 0) return;
            e.preventDefault();
            e.stopPropagation();

            var $span   = $(this);
            if ($span.data('editing')) return;
            var $row    = $span.closest('.impulse-setting-row, .impulse-slider-with-unit').find('.impulse-slider-row');
            var $slider = $row.find('input[type="range"]');
            if (!$slider.length) return;

            var unit     = $row.data('unit'); if (unit === undefined) unit = 'px';
            var min      = parseFloat($slider.attr('min'));
            var max      = parseFloat($slider.attr('max'));
            var startVal = parseFloat($slider.val());
            var startX   = e.clientX;
            var moved    = false;
            
            var rate     = (max - min) / 150;

            function fmtVal(v, shift) {
                var rounded = (shift && rate < 1) ? (Math.round(v * 10) / 10) : Math.round(v);
                var d = rounded + unit;
                if ($row.data('auto') && v == 0) d = 'Auto';
                if ($row.data('zero-text') && v == 0) d = $row.data('zero-text');
                return d;
            }

            function onMove(ev) {
                var dx = ev.clientX - startX;
                if (!moved && Math.abs(dx) < 3) return;
                moved = true;
                document.body.style.cursor = 'ew-resize';
                var mult   = ev.shiftKey ? 0.1 : 1;
                var newVal = startVal + dx * rate * mult;
                newVal = (ev.shiftKey && rate < 1) ? Math.round(newVal * 10) / 10 : Math.round(newVal);
                newVal = Math.max(min, Math.min(max, newVal));
                $slider.val(newVal).trigger('input');
                $span.text(fmtVal(newVal, ev.shiftKey));
            }

            function onUp() {
                document.removeEventListener('mousemove', onMove);
                document.removeEventListener('mouseup', onUp);
                document.body.style.cursor = '';
                if (moved) {
                    $slider.trigger('change');
                    autoSaveAndPreview();
                } else {
                    _openSliderTextInput($span, $slider, $row, unit, min, max, startVal);
                }
            }

            document.addEventListener('mousemove', onMove);
            document.addEventListener('mouseup', onUp);
        });

        function _openSliderTextInput($span, $slider, $row, unit, min, max, currentVal) {

            

            
            
            var $input = $('<input type="number" class="impulse-slider-value-input" data-no-number="1">')
                .val(currentVal).attr('min', min).attr('max', max * 2);
            $span.data('editing', true).replaceWith($input);
            $input[0].focus();
            $input[0].select();

            function applyValue() {
                if ($input.data('done')) return;
                $input.data('done', true);
                var v = parseFloat($input.val());
                if (isNaN(v)) v = currentVal;
                v = Math.max(min, Math.min(max * 2, v));
                $slider.val(Math.min(max, v));
                if (v > max) $slider.attr('max', v);
                $slider.trigger('input');
                var $s = $('<span class="impulse-slider-value">' + v + unit + '</span>');
                $input.replaceWith($s);
                autoSaveAndPreview();
            }
            function cancelEdit() {
                if ($input.data('done')) return;
                $input.data('done', true);
                $input.replaceWith($('<span class="impulse-slider-value">' + currentVal + unit + '</span>'));
            }
            $input.on('keydown', function(ev) {
                if (ev.key === 'Enter')  { ev.preventDefault(); applyValue(); }
                if (ev.key === 'Escape') { ev.preventDefault(); cancelEdit(); }
                ev.stopPropagation();
            });
            $input.on('blur', applyValue);
        }

        function impulseSliderTrack(el) {
            
            if (el.name === 'section_ambient_hue') return;
            var min = parseFloat(el.min) || 0;
            var max = parseFloat(el.max) || 100;
            var val = parseFloat(el.value) || 0;
            var pct = max > min ? ((val - min) / (max - min)) * 100 : 0;
            el.style.background = 'linear-gradient(to right,'+ImpC.muted+' 0%,'+ImpC.muted+' ' + pct + '%,'+ImpC.border+' ' + pct + '%,'+ImpC.border+' 100%)';
        }
        function impulseSliderTrackAll() {
            document.querySelectorAll('.impulse-slider-row input[type="range"]').forEach(impulseSliderTrack);
        }
        
        var _sliderPaintTimer = null;
        function impulseSliderTrackDeferred() {
            clearTimeout(_sliderPaintTimer);
            _sliderPaintTimer = setTimeout(impulseSliderTrackAll, 50);
        }
        
        var _sliderObs = new MutationObserver(impulseSliderTrackDeferred);
        document.querySelectorAll('.impulse-panel-right, .impulse-chat-right, #impulse-global-styles, .impulse-workspace').forEach(function(el) {
            _sliderObs.observe(el, { childList: true, subtree: true });
        });
        
        setTimeout(impulseSliderTrackAll, 300);
        setTimeout(impulseSliderTrackAll, 1000);

        $(document).on('input', '.impulse-slider-row input[type="range"]', function() {
            
            impulseSliderTrack(this);
            
            if ($(this).closest('.impulse-section-anim-layer').length) return;
            
            var $row = $(this).closest('.impulse-slider-row');
            var unit = $row.data('unit');
            if (unit === undefined) unit = 'px';
            var val = $(this).val();
            var display = val + unit;

            if ($row.data('auto') && val == 0) {
                display = 'Auto';
            }
            
            if ($row.data('zero-text') && val == 0) {
                display = $row.data('zero-text');
            }

            var $valSpan = $(this).closest('.impulse-setting-row').find('.impulse-slider-value');
            if (!$valSpan.length) $valSpan = $(this).closest('.impulse-slider-row').find('.impulse-slider-value');
            if (!$valSpan.length) $valSpan = $(this).closest('.impulse-slider-with-unit').find('.impulse-slider-value');
            $valSpan.text(display);

            

            

            

            

            
            var _nm = $(this).attr('name') || '';
            if (_nm.indexOf('screen_') === 0) return;

            autoSaveAndPreview();
        });

        
        $(document).on('input', 'input[name="screen_intensity"]', function() {
            saveScreenBarSettings(false);
        });

        $(document).on('input', '.impulse-speed-inverted', function() {
            var speed = parseInt($(this).val()) || 0;
            var dur = Math.round(2000 - (speed / 100) * 1700);
            $('input[name="screen_duration"]').val(dur);
            saveScreenBarSettings(false);
        });

        $(document).on('mousedown touchstart', '.impulse-richtext-size-slider input[type="range"]', function(e) {
            var $slider = $(this).closest('.impulse-richtext-size-slider');
            $slider.addClass('dragging');
            updateRichtextSizePopup($(this));
        });
        
        $(document).on('mouseup touchend', function() {
            $('.impulse-richtext-size-slider.dragging').removeClass('dragging');
        });
        
        function updateRichtextSizePopup($input) {
            var $slider = $input.closest('.impulse-richtext-size-slider');
            var $popup = $slider.find('.impulse-richtext-size-popup');
            if (!$popup.length) return;
            
            var val = $input.val();
            $popup.text(val + 'px');

            var sliderWidth = $input.width();
            var min = parseFloat($input.attr('min')) || 0;
            var max = parseFloat($input.attr('max')) || 100;
            var percent = (val - min) / (max - min);
            var thumbPos = percent * sliderWidth;
            
            $popup.css('left', thumbPos + 'px');
        }
        
        $(document).on('input', '.impulse-richtext-size-slider input[type="range"]', function() {
            updateRichtextSizePopup($(this));

            autoSaveAndPreview();
        });

        

        
        function collectPageColors() {
            var colors = new Set();
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentDocument) return [];
            
            try {
                var doc = iframe.contentDocument;

                var elements = doc.querySelectorAll('[style]');
                elements.forEach(function(el) {
                    var style = el.getAttribute('style') || '';
                    
                    var hexMatches = style.match(/#[0-9A-Fa-f]{6}/g);
                    if (hexMatches) hexMatches.forEach(function(c) {
                        var lower = c.toLowerCase();
                        
                        if (lower !== ''+ImpC.surface2+'' && lower !== '#ffffff' && lower !== '#000000' && lower !== ''+ImpC.text+'') {
                            colors.add(lower);
                        }
                    });
                });

                var innerSelectors = 'section, h1, h2, h3, h4, h5, h6, p, .impulse-text, a.impulse-button-link, .impulse-button a, .impulse-divider-line, .impulse-icon-box';
                var innerEls = doc.querySelectorAll(innerSelectors);
                innerEls.forEach(function(el) {
                    try {
                        var computed = el.ownerDocument.defaultView.getComputedStyle(el);
                        ['backgroundColor', 'color', 'borderColor'].forEach(function(prop) {
                            var val = computed[prop];
                            if (!val) return;
                            
                            if (val === 'transparent' || 
                                val === 'rgba(0, 0, 0, 0)' ||
                                val === 'rgb(255, 255, 255)' ||
                                val === 'rgb(0, 0, 0)' ||
                                val === 'rgb(29, 35, 39)') return; 

                            var alphaMatch = val.match(/rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*([\d.]+)\s*\)/);
                            if (alphaMatch && parseFloat(alphaMatch[1]) === 0) return;

                            var rgbMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
                            if (rgbMatch) {
                                var hex = '#' + parseInt(rgbMatch[1]).toString(16).padStart(2,'0') +
                                          parseInt(rgbMatch[2]).toString(16).padStart(2,'0') +
                                          parseInt(rgbMatch[3]).toString(16).padStart(2,'0');
                                if (hex !== '#ffffff' && hex !== '#000000' && hex !== ''+ImpC.surface2+'') {
                                    colors.add(hex.toLowerCase());
                                }
                            }
                        });
                    } catch(e) {}
                });
            } catch(e) {}
            
            return Array.from(colors).slice(0, 12); 
        }

        function populatePalette($picker) {
            var colors = collectPageColors();
            var $palette = $picker.find('.impulse-picker-palette');
            var $swatches = $palette.find('.impulse-picker-palette-swatches');
            $swatches.empty();
            
            if (colors.length === 0) {
                $palette.removeClass('has-colors');
                return;
            }
            
            $palette.addClass('has-colors');
            colors.forEach(function(color) {
                $swatches.append('<div class="impulse-picker-palette-swatch" data-color="'+color+'" style="--swatch-color:'+color+'"></div>');
            });
        }

        var dtPickerState = { year: null, month: null, day: null, hour: 12, minute: 0, $trigger: null };
        
        function buildDateTimePicker() {
            var html = '<div class="impulse-datetime-picker">';
            html += '<div class="impulse-datetime-picker-header">';
            html += '<button type="button" class="dt-prev-month"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg></button>';
            html += '<span class="impulse-datetime-picker-month"></span>';
            html += '<button type="button" class="dt-next-month"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg></button>';
            html += '</div>';
            html += '<div class="impulse-datetime-picker-weekdays"><span>Su</span><span>Mo</span><span>Tu</span><span>We</span><span>Th</span><span>Fr</span><span>Sa</span></div>';
            html += '<div class="impulse-datetime-picker-days"></div>';
            html += '<div class="impulse-datetime-picker-time">';
            html += '<input type="number" class="dt-hour" min="0" max="23" value="12">';
            html += '<span>:</span>';
            html += '<input type="number" class="dt-minute" min="0" max="59" value="00">';
            html += '</div>';
            html += '<div class="impulse-datetime-picker-actions">';
            html += '<button type="button" class="dt-cancel">Cancel</button>';
            html += '<button type="button" class="dt-apply primary">Apply</button>';
            html += '</div>';
            html += '</div>';
            return html;
        }
        
        function renderCalendar($picker) {
            var year = dtPickerState.year;
            var month = dtPickerState.month;
            var firstDay = new Date(year, month, 1).getDay();
            var daysInMonth = new Date(year, month + 1, 0).getDate();
            var daysInPrevMonth = new Date(year, month, 0).getDate();
            var today = new Date();
            
            $picker.find('.impulse-datetime-picker-month').text(
                new Date(year, month).toLocaleString('en-US', { month: 'long', year: 'numeric' })
            );
            
            var $days = $picker.find('.impulse-datetime-picker-days').empty();

            for (var i = firstDay - 1; i >= 0; i--) {
                $days.append('<button type="button" class="impulse-datetime-picker-day other-month" data-day="' + (daysInPrevMonth - i) + '" data-month="' + (month - 1) + '">' + (daysInPrevMonth - i) + '</button>');
            }

            for (var d = 1; d <= daysInMonth; d++) {
                var classes = 'impulse-datetime-picker-day';
                if (d === dtPickerState.day && month === dtPickerState.month) classes += ' selected';
                if (d === today.getDate() && month === today.getMonth() && year === today.getFullYear()) classes += ' today';
                $days.append('<button type="button" class="' + classes + '" data-day="' + d + '" data-month="' + month + '">' + d + '</button>');
            }

            var totalCells = firstDay + daysInMonth;
            var remaining = totalCells <= 35 ? 35 - totalCells : 42 - totalCells;
            for (var n = 1; n <= remaining; n++) {
                $days.append('<button type="button" class="impulse-datetime-picker-day other-month" data-day="' + n + '" data-month="' + (month + 1) + '">' + n + '</button>');
            }
        }

        $(document).on('click', '.impulse-datetime-trigger', function(e) {
            e.stopPropagation();
            var $trigger = $(this);
            var $existing = $('.impulse-datetime-picker');
            
            if ($existing.length && $existing.hasClass('open')) {
                $existing.removeClass('open');
                setTimeout(function() { $existing.remove(); }, 200);
                return;
            }

            var val = $trigger.siblings('input[type="hidden"]').val();
            var now = new Date();
            var date = val ? new Date(val) : now;
            if (isNaN(date.getTime())) date = now;
            
            dtPickerState.year = date.getFullYear();
            dtPickerState.month = date.getMonth();
            dtPickerState.day = date.getDate();
            dtPickerState.hour = date.getHours();
            dtPickerState.minute = date.getMinutes();
            dtPickerState.$trigger = $trigger;

            $('.impulse-datetime-picker').remove();

            var $picker = $(buildDateTimePicker());
            $('body').append($picker);
            
            var triggerRect = this.getBoundingClientRect();
            var pickerHeight = 320;
            var top = triggerRect.bottom + 4;
            if (top + pickerHeight > window.innerHeight - 10) {
                top = triggerRect.top - pickerHeight - 4;
            }
            
            $picker.css({
                top: top + 'px',
                left: (triggerRect.left) + 'px'
            });

            $picker.find('.dt-hour').val(dtPickerState.hour.toString().padStart(2, '0'));
            $picker.find('.dt-minute').val(dtPickerState.minute.toString().padStart(2, '0'));
            
            renderCalendar($picker);
            
            setTimeout(function() { $picker.addClass('open'); }, 10);
        });

        $(document).on('click', '.dt-prev-month', function(e) {
            e.stopPropagation();
            dtPickerState.month--;
            if (dtPickerState.month < 0) {
                dtPickerState.month = 11;
                dtPickerState.year--;
            }
            renderCalendar($(this).closest('.impulse-datetime-picker'));
        });
        
        $(document).on('click', '.dt-next-month', function(e) {
            e.stopPropagation();
            dtPickerState.month++;
            if (dtPickerState.month > 11) {
                dtPickerState.month = 0;
                dtPickerState.year++;
            }
            renderCalendar($(this).closest('.impulse-datetime-picker'));
        });

        $(document).on('click', '.impulse-datetime-picker-day', function(e) {
            e.stopPropagation();
            var $this = $(this);
            var $picker = $this.closest('.impulse-datetime-picker');
            var day = parseInt($this.data('day'));
            var month = parseInt($this.data('month'));

            if (month < 0) {
                month = 11;
                dtPickerState.year--;
            } else if (month > 11) {
                month = 0;
                dtPickerState.year++;
            }
            
            dtPickerState.month = month;
            dtPickerState.day = day;
            renderCalendar($picker);
        });

        $(document).on('change', '.dt-hour, .dt-minute', function() {
            var $picker = $(this).closest('.impulse-datetime-picker');
            dtPickerState.hour = parseInt($picker.find('.dt-hour').val()) || 0;
            dtPickerState.minute = parseInt($picker.find('.dt-minute').val()) || 0;
        });

        $(document).on('click', '.dt-cancel', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-datetime-picker');
            $picker.removeClass('open');
            setTimeout(function() { $picker.remove(); }, 200);
        });

        $(document).on('click', '.dt-apply', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-datetime-picker');

            var date = new Date(dtPickerState.year, dtPickerState.month, dtPickerState.day, dtPickerState.hour, dtPickerState.minute);
            var isoStr = date.getFullYear() + '-' + 
                String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                String(date.getDate()).padStart(2, '0') + 'T' + 
                String(date.getHours()).padStart(2, '0') + ':' + 
                String(date.getMinutes()).padStart(2, '0');

            var displayStr = date.toLocaleString('en-US', {month:'short', day:'numeric', year:'numeric', hour:'2-digit', minute:'2-digit'});
            dtPickerState.$trigger.text(displayStr);
            dtPickerState.$trigger.siblings('input[type="hidden"]').val(isoStr).trigger('change');
            
            $picker.removeClass('open');
            setTimeout(function() { $picker.remove(); }, 200);

            if (typeof autoSaveAndRefresh === 'function') autoSaveAndRefresh();
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.impulse-datetime-picker, .impulse-datetime-trigger').length) {
                var $picker = $('.impulse-datetime-picker');
                if ($picker.length) {
                    $picker.removeClass('open');
                    setTimeout(function() { $picker.remove(); }, 200);
                }
            }
        });

        var colorSwatchClickTimer = null;

        window._pickerHideTimer = null;
        $(document).on('mouseenter', '.impulse-color-picker', function() {
            clearTimeout(window._pickerHideTimer);
        });
        $(document).on('mouseleave', '.impulse-color-picker', function() {
            clearTimeout(window._pickerHideTimer);
            window._pickerHideTimer = setTimeout(function() {
                $('.impulse-color-picker').removeClass('open dragging-gradient dragging-hue');
            }, 3000);
        });

        $(document).on('click', '.impulse-color-swatch', function(e) {
            e.stopPropagation();
            var $swatch = $(this);
            var $row = $swatch.closest('.impulse-color-setting, .impulse-color-row');
            var $picker = $row.find('.impulse-color-picker');

            if (!$picker.length) {
                var $input = $row.find('.impulse-color-text, input[type="hidden"]');
                var value = $input.val() || $swatch.css('--swatch-color') || '#000000';
                if (value.indexOf('#') !== 0) value = '#000000';

                var r = parseInt(value.substr(1,2), 16) || 0;
                var g = parseInt(value.substr(3,2), 16) || 0;
                var b = parseInt(value.substr(5,2), 16) || 0;
                var hexVal = value;

                var max = Math.max(r, g, b), min = Math.min(r, g, b);
                var h = 0, s = 0, v = max / 255;
                var d = max - min;
                s = max === 0 ? 0 : d / max;
                if (max !== min) {
                    switch (max) {
                        case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                        case g: h = (b - r) / d + 2; break;
                        case b: h = (r - g) / d + 4; break;
                    }
                    h /= 6;
                }
                var hue = Math.round(h * 360);
                var sat = Math.round(s * 100);
                var val = Math.round(v * 100);
                var hueColor = 'hsl('+hue+',100%,50%)';
                var alphaGradient = 'linear-gradient(to right, transparent, '+hexVal+')';
                
                var pickerHtml = '<div class="impulse-color-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'" data-alpha="100">';

                pickerHtml += '<div class="impulse-picker-gradient" style="background-color:'+hueColor+'">';
                pickerHtml += '<div class="impulse-picker-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div></div>';
                pickerHtml += '<div class="impulse-picker-sliders"><div class="impulse-picker-slider-row"><div class="impulse-picker-hue"><div class="impulse-picker-thumb" style="left:'+((hue/360)*100)+'%"></div></div></div></div>';
                pickerHtml += '<div class="impulse-picker-tools">';
                pickerHtml += '<div class="impulse-picker-hex"><input type="text" value="'+hexVal+'" placeholder="#000000"></div>';
                pickerHtml += '<button type="button" class="impulse-picker-eyedropper" title="Pick from screen"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z"/></svg></button>';
                pickerHtml += '</div></div>';
                
                $swatch.after(pickerHtml);
                $picker = $row.find('.impulse-color-picker');
            }
            
            var wasOpen = $picker.hasClass('open');
            var isChat = $swatch.closest('.impulse-chat-right').length > 0;

            $('.impulse-color-picker').removeClass('open dragging-gradient dragging-hue');
            gradientDragging = false;
            activeGradient = null;
            hueDragging = false;
            activeHue = null;
            alphaDragging = false;
            activeAlpha = null;

            if (wasOpen) return;

            clearTimeout(colorSwatchClickTimer);
            colorSwatchClickTimer = setTimeout(function() {
                populatePalette($picker);
                
                var pickerHeight = 170;
                var pickerWidth = 172;
                var left, top;
                var swatchRect = $swatch[0].getBoundingClientRect();

                var inBar = $swatch.closest('#impulse-screen-bar').length > 0;
                
                if (inBar) {
                    left = swatchRect.left;
                    top = swatchRect.top - pickerHeight - 6;
                    if (top < 10) top = 10;
                } else if (isChat) {
                    var $chatRight = $('.impulse-chat-right');
                    var chatRect = $chatRight.length ? $chatRight[0].getBoundingClientRect() : null;
                    left = chatRect ? (chatRect.left - pickerWidth) : (swatchRect.left - pickerWidth);
                    top = swatchRect.top - 10;
                    if (top + pickerHeight > window.innerHeight - 10) top = swatchRect.bottom - pickerHeight + 10;
                    top = Math.max(10, Math.min(top, window.innerHeight - pickerHeight - 10));
                } else {
                    var $panelRight = $swatch.closest('.impulse-panel-right');
                    var panelRect = ($panelRight.length && $panelRight.width() > 50) ? $panelRight[0].getBoundingClientRect() : null;
                    if (panelRect) {
                        left = panelRect.left - pickerWidth - 4;
                        top = swatchRect.top - 10;
                        if (top + pickerHeight > window.innerHeight - 10) top = swatchRect.bottom - pickerHeight + 10;
                        top = Math.max(10, Math.min(top, window.innerHeight - pickerHeight - 10));
                    } else {
                        left = Math.max(10, swatchRect.left - pickerWidth - 4);
                        top = swatchRect.bottom + 4;
                    }
                }
                
                left = Math.max(10, Math.min(left, window.innerWidth - pickerWidth - 10));
                
                $picker.css({
                    top: top + 'px',
                    left: left + 'px',
                    width: pickerWidth + 'px',
                    maxWidth: 'none',
                    position: 'fixed',
                    zIndex: 100001
                });
                
                $picker.addClass('open');
                
                clearTimeout(window._pickerHideTimer);
                window._pickerHideTimer = setTimeout(function() {
                    $('.impulse-color-picker').removeClass('open dragging-gradient dragging-hue');
                }, 3000);

                setTimeout(function() {
                    updateColorFromPicker($picker, true);
                }, 10);
            }, 200); 
        });

        $(document).on('dblclick', '.impulse-color-swatch', function(e) {
            if ($(this).closest('.impulse-chat-right').length) return; 
            e.stopPropagation();

            clearTimeout(colorSwatchClickTimer);
            
            var $swatch = $(this);
            var $row = $swatch.closest('.impulse-color-setting, .impulse-color-row');
            var $picker = $row.find('.impulse-color-picker');

            var defaultColor = $swatch.data('default');
            if (!defaultColor) defaultColor = $picker.find('.impulse-picker-palette').data('default');
            if (!defaultColor) defaultColor = 'transparent';

            $swatch.css('--swatch-color', defaultColor);
            var $input = $row.find('.impulse-color-text');
            var inputName = $input.attr('name') || '';
            $input.val(defaultColor).trigger('input').trigger('change');

            $picker.removeClass('open dragging-gradient dragging-hue');

            if (inputName.startsWith('card_design_')) {
                autoSaveAndPreview();
            } else if (inputName.startsWith('color_') && !selectedElementType) {
                
            } else if ($(this).closest('.impulse-section-anim-color-wrap').length) {
                
            } else {
                autoSaveAndPreview();
            }
        });

        $(document).on('click', '.impulse-picker-palette-swatch', function(e) {
            e.stopPropagation();
            var color = $(this).data('color');
            var $picker = $(this).closest('.impulse-color-picker');
            var $row = $picker.closest('.impulse-color-setting, .impulse-color-row');

            

            

            $row.find('.impulse-color-text').val(color).trigger('input').trigger('change');

            try {
                var c = String(color || '');
                var hexVal = c;
                if (c.indexOf('rgba') === 0) {
                    var m = c.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                    if (m) hexVal = '#' + (+m[1]).toString(16).padStart(2,'0')
                                       + (+m[2]).toString(16).padStart(2,'0')
                                       + (+m[3]).toString(16).padStart(2,'0');
                }
                if (hexVal[0] === '#' && hexVal.length === 7) {
                    var r = parseInt(hexVal.substr(1,2), 16);
                    var g = parseInt(hexVal.substr(3,2), 16);
                    var b = parseInt(hexVal.substr(5,2), 16);
                    var max = Math.max(r,g,b), min = Math.min(r,g,b);
                    var h = 0, s = 0, v = max / 255;
                    var d = max - min;
                    s = max === 0 ? 0 : d / max;
                    if (max !== min) {
                        switch (max) {
                            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                            case g: h = (b - r) / d + 2; break;
                            case b: h = (r - g) / d + 4; break;
                        }
                        h /= 6;
                    }
                    var hue = Math.round(h * 360);
                    var sat = Math.round(s * 100);
                    var val = Math.round(v * 100);
                    $picker.attr('data-hue', hue).attr('data-sat', sat).attr('data-val', val);
                    $picker.find('.impulse-picker-gradient').css('background-color','hsl('+hue+',100%,50%)');
                    $picker.find('.impulse-picker-cursor').css({left:sat+'%', top:(100-val)+'%'});
                    $picker.find('.impulse-picker-hue .impulse-picker-thumb').css('left',((hue/360)*100)+'%');
                    $picker.find('.impulse-picker-alpha').css('--alpha-gradient','linear-gradient(to right, transparent, '+hexVal+')');
                    $picker.find('.impulse-picker-hex input').val(hexVal);
                }
            } catch (_e) {}
        });

        

        

        $(document).on('click', '.impulse-picker-eyedropper', function(e) {
            e.stopPropagation();

            

            var $picker = $(this).closest('.impulse-color-picker');
            if ($picker.is('[data-picker-row]') ||
                $picker.closest('.impulse-chat-right, #settings-chat-panel').length) {
                return;
            }
            var $row = $picker.closest('.impulse-color-setting, .impulse-color-row');
            if (!window.EyeDropper) {
                window.showToast && window.showToast('Eyedropper not supported. Try Chrome or Edge.', 'error');
                return;
            }
            new EyeDropper().open().then(function(result) {
                $row.find('.impulse-color-text').val(result.sRGBHex).trigger('input').trigger('change');
            }).catch(function() {});
        });

        $(document).on('click', '.impulse-picker-reset', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-color-picker');
            var $row = $picker.closest('.impulse-color-setting, .impulse-color-row');
            var $palette = $(this).closest('.impulse-picker-palette');
            var fieldName = $row.data('name') || $row.find('input[type="hidden"]').attr('name');

            var elementDefaults = {
                title: { color: ''+ImpC.surface2+'' },
                text: { color: '#666666' },
                button: { text_color: '#ffffff', bg_color: ''+ImpC.surface2+'', border_color: ''+ImpC.surface2+'', hover_text_color: '#ffffff', hover_bg_color: '#333333', hover_border_color: '#333333' },
                divider: { color: ''+ImpC.text+'', icon_color: ''+ImpC.surface2+'', icon_bg_color: ''+ImpC.text+'', element_icon_color: ''+ImpC.surface2+'', element_icon_bg_color: ''+ImpC.text+'', element_text_color: ''+ImpC.surface2+'' },
                icon_card: { icon_color: ''+ImpC.surface2+'', bg_color: ''+ImpC.text+'', hover_color: '#333333' },
                icon_box: { icon_color: ''+ImpC.surface2+'', bg_color: ''+ImpC.light+'', title_color: ''+ImpC.surface2+'', desc_color: '#666666' },
                social: { icon_color: '#ffffff', bg_color: ''+ImpC.surface2+'', hover_color: '#333333' },
                section: { bg_color: 'transparent', overlay_color: 'rgba(0,0,0,0.5)' },
                container: { bg_color: 'transparent' },
                grid: { bg_color: 'transparent' },
                rows: { bg_color: 'transparent', border_color: ''+ImpC.text+'' },
                stack: { bg_color: 'transparent' },
                inline: { bg_color: 'transparent' },
                counter: { number_color: ''+ImpC.surface2+'', label_color: '#666666' },
                alert: { bg_color: ''+ImpC.light+'', border_color: '#0ea5e9', text_color: '#0c4a6e', icon_color: '#0ea5e9' },
                tabs: { tab_bg: ''+ImpC.light+'', tab_active_bg: '#ffffff', tab_text: '#6b7280', tab_active_text: ''+ImpC.surface2+'', content_bg: '#ffffff', border_color: ''+ImpC.text+'' },
                unfold: { header_bg: ''+ImpC.light+'', header_color: ''+ImpC.surface2+'', content_bg: '#ffffff', border_color: ''+ImpC.text+'' },
                form: { form_bg_color: '#ffffff', form_border_color: 'transparent', field_bg_color: '#ffffff', field_border_color: ''+ImpC.text+'', field_text_color: ''+ImpC.surface2+'', label_color: '#374151', button_bg_color: ''+ImpC.surface2+'', button_text_color: '#ffffff' },
                title: { line_1_color: ''+ImpC.surface2+'', line_1_grad_1: ''+ImpC.surface2+'', line_1_grad_2: '', line_1_fill: 'solid' },
                image: { overlay_color: 'rgba(0,0,0,0.5)' },
                video: { overlay_color: 'rgba(0,0,0,0.5)' }
            };

            var defaultColor = '#ffffff';
            if (selectedElementType && elementDefaults[selectedElementType] && elementDefaults[selectedElementType][fieldName]) {
                defaultColor = elementDefaults[selectedElementType][fieldName];
            }

            
            
            var r = 255, g = 255, b = 255, a = 1;
            if (defaultColor.startsWith('rgba')) {
                var match = defaultColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                if (match) {
                    r = parseInt(match[1]);
                    g = parseInt(match[2]);
                    b = parseInt(match[3]);
                    a = match[4] ? parseFloat(match[4]) : 1;
                }
            } else if (defaultColor.startsWith('#')) {
                var hex = defaultColor.length === 4 ? 
                    '#' + defaultColor[1]+defaultColor[1] + defaultColor[2]+defaultColor[2] + defaultColor[3]+defaultColor[3] : defaultColor;
                r = parseInt(hex.substr(1,2), 16);
                g = parseInt(hex.substr(3,2), 16);
                b = parseInt(hex.substr(5,2), 16);
            }

            var hsv = rgbToHsv(r, g, b);
            $picker.data('hue', Math.round(hsv.h));
            $picker.data('sat', Math.round(hsv.s));
            $picker.data('val', Math.round(hsv.v));
            $picker.data('alpha', Math.round(a * 100));

            updateColorFromPicker($picker);
        });

        $(document).on('click', '.impulse-picker-apply', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-color-picker');
            var $row = $picker.closest('.impulse-color-setting, .impulse-color-row');
            var inputName = $row.find('.impulse-color-text').attr('name') || '';

            $picker.removeClass('open dragging-gradient dragging-hue');

            if (inputName.startsWith('cell_') && (selectedElementType === 'rows' || selectedElementType === 'columns')) {
                
            } else if (inputName.startsWith('cell_bg_') || inputName.startsWith('card_design_')) {
                autoSaveAndRefresh();
            } else if (inputName.startsWith('color_')) {
                
                $row.find('.impulse-color-text').trigger('change');
            } else if ($row.closest('.impulse-section-anim-color-wrap').length) {
                
                $row.find('.impulse-color-text').trigger('change');
            } else {
                autoSaveAndPreview();
            }
        });

        

        

        

        
        
        var _IMP_PICKER_HIT_BUFFER = 32;
        $(document).on('click', function(e) {
            if ($(e.target).closest('.impulse-color-picker, .impulse-color-swatch').length) return;

            var openPickers = document.querySelectorAll('.impulse-color-picker.open');
            for (var i = 0; i < openPickers.length; i++) {
                var rect = openPickers[i].getBoundingClientRect();
                if (e.clientX >= rect.left - _IMP_PICKER_HIT_BUFFER &&
                    e.clientX <= rect.right + _IMP_PICKER_HIT_BUFFER &&
                    e.clientY >= rect.top - _IMP_PICKER_HIT_BUFFER &&
                    e.clientY <= rect.bottom + _IMP_PICKER_HIT_BUFFER) {
                    return;
                }
            }
            $('.impulse-color-picker.open').each(function() {
                var $p = $(this);
                try { updateColorFromPicker($p); } catch (_err) {}
            });
            $('.impulse-color-picker').removeClass('open dragging-gradient dragging-hue');
        });

        function updateColorFromPicker($picker, suppressChange) {
            
            var hue = parseFloat($picker.data('hue'));
            if (isNaN(hue)) hue = 0;
            var sat = parseFloat($picker.data('sat'));
            if (isNaN(sat)) sat = 100;
            var val = parseFloat($picker.data('val'));
            if (isNaN(val)) val = 100;
            var alpha = parseFloat($picker.data('alpha'));
            if (isNaN(alpha)) alpha = 100;
            alpha = alpha / 100;
            
            var rgb = hsvToRgb(hue, sat, val);
            var hexVal = '#' + rgb.r.toString(16).padStart(2,'0') + rgb.g.toString(16).padStart(2,'0') + rgb.b.toString(16).padStart(2,'0');

            var hexDisplay = alpha < 1 ? (hexVal + Math.round(alpha * 255).toString(16).padStart(2, '0')) : hexVal;

            $picker.find('.impulse-picker-gradient').css('background-color', 'hsl('+hue+',100%,50%)');

            var cursorLeft = Math.max(0, Math.min(100, sat));
            var cursorTop = Math.max(0, Math.min(100, 100 - val));
            $picker.find('.impulse-picker-cursor').css({ left: cursorLeft+'%', top: cursorTop+'%' });

            var $hueSlider = $picker.find('.impulse-picker-hue');
            var sliderWidth = $hueSlider.width();
            var trackPadding = 6;
            if (sliderWidth > 0) {
                var hueThumbPx = trackPadding + (hue / 360) * (sliderWidth - trackPadding * 2);
                $hueSlider.find('.impulse-picker-thumb').css('left', hueThumbPx + 'px');
            }

            var $alphaSlider = $picker.find('.impulse-picker-alpha');
            if ($alphaSlider.length) {
                $alphaSlider.css('--alpha-gradient', 'linear-gradient(to right, transparent, '+hexVal+')');
                var alphaWidth = $alphaSlider.width();
                if (alphaWidth > 0) {
                    var alphaThumbPx = trackPadding + alpha * (alphaWidth - trackPadding * 2);
                    $alphaSlider.find('.impulse-picker-thumb').css('left', alphaThumbPx + 'px');
                }
            }

            

            

            
            
            var $hexLive = $picker.find('.impulse-picker-hex input');
            if (!$hexLive.is(':focus')) {
                $hexLive.val(hexDisplay);
            }
            var $alphaInput = $picker.find('.impulse-picker-alpha-input input');
            if ($alphaInput.length) {
                $alphaInput.val(Math.round(alpha*100)+'%');
            }

            var $row = $picker.closest('.impulse-color-setting, .impulse-color-row');
            var colorVal = alpha < 1 ? 'rgba('+rgb.r+','+rgb.g+','+rgb.b+','+alpha+')' : hexVal;
            var $input = $row.find('.impulse-color-text');
            var inputName = $input.attr('name') || '';

            
            
            $input.val(colorVal);
            if (!suppressChange) $input.trigger('change');
            $row.find('.impulse-color-swatch').css('--swatch-color', colorVal);

            
            
            if (inputName.startsWith('cell_') && (selectedElementType === 'rows' || selectedElementType === 'columns')) {
                
            } else if (inputName.startsWith('cell_bg_')) {
                autoSaveAndRefresh();
            } else if (inputName.startsWith('color_') && !selectedElementType) {
                
            } else if (inputName === 'screen_gradient_color1' || inputName === 'screen_gradient_color2') {
                
                if (typeof _liveUpdateGradientOverlay === 'function') _liveUpdateGradientOverlay();
                if (typeof saveScreenBarSettings === 'function') saveScreenBarSettings(false);
            } else if (inputName.startsWith('section_anim_')) {

                
                
            } else if (selectedElementType === 'rows' || selectedElementType === 'columns') {
                autoSaveAndPreview();
            } else {
                autoSaveAndPreview();
            }
        }

        function updateHexInputFromPicker($picker) {
            if (!$picker || !$picker.length) return;
            var hue = parseFloat($picker.data('hue')) || 0;
            var sat = parseFloat($picker.data('sat')) || 100;
            var val = parseFloat($picker.data('val')) || 100;
            var aPct = parseFloat($picker.data('alpha'));
            if (isNaN(aPct)) aPct = 100;
            var rgb = hsvToRgb(hue, sat, val);
            var hexVal = '#' + rgb.r.toString(16).padStart(2,'0') + rgb.g.toString(16).padStart(2,'0') + rgb.b.toString(16).padStart(2,'0');
            
            if (aPct < 100) hexVal += Math.round(aPct / 100 * 255).toString(16).padStart(2, '0');
            $picker.find('.impulse-picker-hex input').val(hexVal);
        }

        

        

        
        
        var gradientDragging = false;
        var activeGradient = null;
        $(document).on('mousedown', '.impulse-picker-gradient', function(e) {
            if ($(this).closest('.impulse-color-picker[data-picker-row]').length) return;
            e.preventDefault(); 
            gradientDragging = true;
            activeGradient = $(this);
            activeGradient.closest('.impulse-color-picker').addClass('dragging-gradient');
            handleGradientMove($(this), e);
        });
        $(document).on('mousemove', function(e) {
            if (gradientDragging && activeGradient) {
                handleGradientMove(activeGradient, e);
            }
        });
        $(document).on('mouseup', function() { 
            if (activeGradient) {
                var $picker = activeGradient.closest('.impulse-color-picker');
                $picker.removeClass('dragging-gradient');
                
                updateHexInputFromPicker($picker);
            }
            gradientDragging = false; 
            activeGradient = null;
        });
        
        function handleGradientMove($gradient, e) {
            if (!$gradient.length) return;
            var rect = $gradient[0].getBoundingClientRect();
            if (rect.width <= 0 || rect.height <= 0) return;

            var x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
            var y = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
            
            var $picker = $gradient.closest('.impulse-color-picker');
            $picker.data('sat', Math.round(x * 100));
            $picker.data('val', Math.round((1 - y) * 100));
            updateColorFromPicker($picker);
        }

        
        var hueDragging = false;
        var activeHue = null;
        $(document).on('mousedown', '.impulse-picker-hue', function(e) {
            if ($(this).closest('.impulse-color-picker[data-picker-row]').length) return;
            e.preventDefault();
            hueDragging = true;
            activeHue = $(this);
            activeHue.closest('.impulse-color-picker').addClass('dragging-hue');
            handleHueMove($(this), e);
        });
        $(document).on('mousemove', function(e) {
            if (hueDragging && activeHue) {
                handleHueMove(activeHue, e);
            }
        });
        $(document).on('mouseup', function() { 
            if (activeHue) {
                var $picker = activeHue.closest('.impulse-color-picker');
                $picker.removeClass('dragging-hue');
                
                updateHexInputFromPicker($picker);
            }
            hueDragging = false; 
            activeHue = null;
        });
        
        function handleHueMove($hue, e) {
            if (!$hue.length) return;
            var rect = $hue[0].getBoundingClientRect();
            var trackPadding = 6;
            var trackWidth = rect.width - trackPadding * 2;
            if (trackWidth <= 0) return;

            var relX = e.clientX - rect.left - trackPadding;
            var x = Math.max(0, Math.min(1, relX / trackWidth));
            var $picker = $hue.closest('.impulse-color-picker');
            $picker.data('hue', Math.round(x * 360));
            updateColorFromPicker($picker);
        }

        var alphaDragging = false;
        var activeAlpha = null;
        $(document).on('mousedown', '.impulse-picker-alpha', function(e) {
            if ($(this).closest('.impulse-color-picker[data-picker-row]').length) return;
            alphaDragging = true;
            activeAlpha = $(this);
            handleAlphaMove($(this), e);
        });
        $(document).on('mousemove', function(e) {
            if (alphaDragging && activeAlpha) {
                handleAlphaMove(activeAlpha, e);
            }
        });
        $(document).on('mouseup', function() { 
            if (activeAlpha) {
                
                updateHexInputFromPicker(activeAlpha.closest('.impulse-color-picker'));
            }
            alphaDragging = false; 
            activeAlpha = null;
        });
        
        function handleAlphaMove($alpha, e) {
            if (!$alpha.length) return;
            var rect = $alpha[0].getBoundingClientRect();
            var trackPadding = 6;
            var trackWidth = rect.width - trackPadding * 2;
            if (trackWidth <= 0) return;

            var relX = e.clientX - rect.left - trackPadding;
            var x = Math.max(0, Math.min(1, relX / trackWidth));
            var $picker = $alpha.closest('.impulse-color-picker');
            $picker.data('alpha', Math.round(x * 100));
            updateColorFromPicker($picker);
        }

        $(document).on('input', '.impulse-picker-hex input', function() {
            if ($(this).closest('.impulse-chat-right').length) return; 
            var val = $(this).val().trim();

            var m = /^#([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/.exec(val);
            if (!m) return;
            var body = m[1];
            var r = parseInt(body.substr(0,2), 16);
            var g = parseInt(body.substr(2,2), 16);
            var b = parseInt(body.substr(4,2), 16);
            var hsv = rgbToHsv(r, g, b);

            var $picker = $(this).closest('.impulse-color-picker');
            $picker.data('hue', Math.round(hsv.h));
            $picker.data('sat', Math.round(hsv.s));
            $picker.data('val', Math.round(hsv.v));
            if (m[2]) {
                $picker.data('alpha', Math.round(parseInt(m[2], 16) / 255 * 100));
            } else if (parseInt($picker.data('alpha'), 10) === 0) {

                

                $picker.data('alpha', 100);
            }
            updateColorFromPicker($picker);
        });

        $(document).on('input', '.impulse-picker-alpha-input input', function() {
            var val = parseInt($(this).val()) || 100;
            val = Math.max(0, Math.min(100, val));
            
            var $picker = $(this).closest('.impulse-color-picker');
            $picker.data('alpha', val);
            updateColorFromPicker($picker);
        });

        $(document).on('input', '.impulse-color-text', function() {
            var val = $(this).val().trim();
            var $row = $(this).closest('.impulse-color-setting, .impulse-color-row');
            var $picker = $row.find('.impulse-color-picker');
            var inputName = $(this).attr('name') || '';
            var r, g, b, a = 1;
            
            if (/^#[0-9A-Fa-f]{6}$/.test(val)) {
                r = parseInt(val.substr(1,2), 16);
                g = parseInt(val.substr(3,2), 16);
                b = parseInt(val.substr(5,2), 16);
            } else if (val.startsWith('rgba')) {
                var match = val.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                if (match) {
                    r = parseInt(match[1]);
                    g = parseInt(match[2]);
                    b = parseInt(match[3]);
                    a = match[4] ? parseFloat(match[4]) : 1;
                }
            } else if (val === 'transparent') {
                r = 255; g = 255; b = 255; a = 0;
            } else {
                
                $row.find('.impulse-color-swatch').css('--swatch-color', val || 'transparent');
                
                if (inputName.startsWith('cell_')) {
                    
                } else if (inputName.startsWith('color_')) {
                    
                } else {
                    
                    autoSaveAndPreview();
                }
                return;
            }
            
            var hsv = rgbToHsv(r, g, b);
            $picker.data('hue', Math.round(hsv.h));
            $picker.data('sat', Math.round(hsv.s));
            $picker.data('val', Math.round(hsv.v));
            $picker.data('alpha', Math.round(a * 100));

            var hexVal = '#' + r.toString(16).padStart(2,'0') + g.toString(16).padStart(2,'0') + b.toString(16).padStart(2,'0');
            $picker.find('.impulse-picker-gradient').css('background-color', 'hsl('+hsv.h+',100%,50%)');
            $picker.find('.impulse-picker-cursor').css({ left: hsv.s+'%', top: (100-hsv.v)+'%' });

            var trackPadding = 6;
            var $hueSlider = $picker.find('.impulse-picker-hue');
            var hueWidth = $hueSlider.width();
            if (hueWidth > 0) {
                var hueThumbPx = trackPadding + (hsv.h / 360) * (hueWidth - trackPadding * 2);
                $hueSlider.find('.impulse-picker-thumb').css('left', hueThumbPx + 'px');
            }
            
            $picker.find('.impulse-picker-alpha').css('--alpha-gradient', 'linear-gradient(to right, transparent, '+hexVal+')');
            var $alphaSlider = $picker.find('.impulse-picker-alpha');
            var alphaWidth = $alphaSlider.width();
            if (alphaWidth > 0) {
                var alphaThumbPx = trackPadding + a * (alphaWidth - trackPadding * 2);
                $alphaSlider.find('.impulse-picker-thumb').css('left', alphaThumbPx + 'px');
            }
            
            $picker.find('.impulse-picker-hex input').val(hexVal);
            $picker.find('.impulse-picker-alpha-input input').val(Math.round(a*100)+'%');

            var colorVal = a < 1 ? 'rgba('+r+','+g+','+b+','+a+')' : hexVal;
            $row.find('.impulse-color-swatch').css('--swatch-color', colorVal);

            if (inputName.startsWith('cell_')) {
                
            } else if (inputName.startsWith('color_')) {
                
            } else {
                
                if (inputName === 'shape_color' || inputName.startsWith('shape_color_')) {
                    var $form = $('#impulse-settings-body');
                    var colorsArr = [];
                    
                    var c1 = $form.find('input[name="shape_color"]').val();
                    if (c1) colorsArr.push(c1);
                    var ci2 = 2;
                    while (true) {
                        var $ci = $form.find('input[name="shape_color_' + ci2 + '"]');
                        if (!$ci.length) break;
                        colorsArr.push($ci.val() || ''+ImpC.surface2+'');
                        ci2++;
                    }
                    if (colorsArr.length) {
                        $form.find('input[name="colors"]').val(JSON.stringify(colorsArr));
                    }
                }
                
                autoSaveAndPreview();
            }
        });

        $(document).on('change', '.impulse-panel-right input[name^="shape_color"]', function() {
            if (selectedElementType !== 'shape') return;
            var $form = $('#impulse-settings-body');
            var colorsArr = [];
            var c1 = $form.find('input[name="shape_color"]').val();
            if (c1) colorsArr.push(c1);
            var ci = 2;
            while (true) {
                var $ci = $form.find('input[name="shape_color_' + ci + '"]');
                if (!$ci.length) break;
                colorsArr.push($ci.val() || ''+ImpC.surface2+'');
                ci++;
            }
            if (colorsArr.length) {
                $form.find('input[name="colors"]').val(JSON.stringify(colorsArr));
            }
        });

        $(document).on('input', '.impulse-panel-right input[type="text"], .impulse-panel-right textarea', function() {
            
            if (this.tagName === 'TEXTAREA') { this.style.height = 'auto'; this.style.height = (this.scrollHeight + 2) + 'px'; }
            
            if ($(this).closest('.impulse-color-picker').length) return;
            
            if ($(this).hasClass('impulse-unfold-title') || $(this).hasClass('impulse-unfold-content')) return;
            
            var inputName = $(this).attr('name') || '';
            if (inputName.startsWith('cell_')) return;
            
            if (inputName.startsWith('menu_label') || inputName.startsWith('menu_url')) return;
            
            if (inputName.indexOf('_link_label') !== -1 || inputName.indexOf('_link_url') !== -1) return;

            if (selectedElementType === 'header' || selectedElementType === 'footer') {
                autoSaveAndRefresh();
            } else {
                autoSaveAndPreview();
            }
            
            if (this.tagName === 'TEXTAREA') {
                this.style.height = 'auto';
                this.style.height = (this.scrollHeight + 2) + 'px';
            }
        });

        
        $(document).on('change', '.impulse-panel-right input[type="radio"]', function() {
            autoSaveAndPreview(true);
        });

        
        var _fontPickerOpen = null; 
        var _fontPickerOriginal = ''; 
        var _fontPickerIdx = -1; 

        function fontPickerApply($picker, idx, commit) {
            var $opts = $picker.find('.impulse-font-option');
            if (idx < 0 || idx >= $opts.length) return;
            _fontPickerIdx = idx;
            $opts.removeClass('active');
            var $opt = $opts.eq(idx);
            $opt.addClass('active');
            
            var container = $picker.find('.impulse-font-options')[0];
            var optEl = $opt[0];
            if (container && optEl) {
                var cTop = container.scrollTop, cH = container.clientHeight;
                var oTop = optEl.offsetTop, oH = optEl.offsetHeight;
                if (oTop < cTop) container.scrollTop = oTop;
                else if (oTop + oH > cTop + cH) container.scrollTop = oTop + oH - cH;
            }
            var val = $opt.data('value') || '';
            var label = $opt.text();
            $picker.find('input[type="hidden"]').val(val);
            var $trigger = $picker.find('.impulse-font-trigger');
            $trigger.find('.impulse-font-trigger-label').text(label);
            
            $trigger.css('font-family', val || '');
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var elementType = $('.impulse-panel-right').data('element-type') || selectedElementType;
            var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
            if (doc && elementId) {
                var cssVal = val || '';
                var targets = [];
                if (elementType === 'text') {
                    targets = doc.querySelectorAll('.impulse-el[data-id="' + elementId + '"] .impulse-text');
                } else if (elementType === 'title') {
                    
                    var pickerName = $picker.find('input[type="hidden"]').attr('name') || '';
                    var lineMatch = pickerName.match(/^line_(\d+)_font$/);
                    if (lineMatch) {
                        targets = doc.querySelectorAll('.impulse-el[data-id="' + elementId + '"] .impulse-dt-line[data-line="' + lineMatch[1] + '"]');
                    } else {
                        
                        targets = doc.querySelectorAll('.impulse-el[data-id="' + elementId + '"] .impulse-display-text h1,.impulse-el[data-id="' + elementId + '"] .impulse-display-text h2,.impulse-el[data-id="' + elementId + '"] .impulse-display-text h3,.impulse-el[data-id="' + elementId + '"] .impulse-display-text h4,.impulse-el[data-id="' + elementId + '"] .impulse-display-text h5,.impulse-el[data-id="' + elementId + '"] .impulse-display-text h6,.impulse-el[data-id="' + elementId + '"] .impulse-display-text p,.impulse-el[data-id="' + elementId + '"] .impulse-display-text div');
                    }
                } else if (elementType === 'title') {
                    targets = doc.querySelectorAll('.impulse-el[data-id="' + elementId + '"] .impulse-la-asset');
                }

                
                if (elementType === 'title') {
                    var _laTargets = doc.querySelectorAll('.impulse-el[data-id="' + elementId + '"] .impulse-la-asset');
                    if (_laTargets.length) {
                        targets = Array.prototype.slice.call(targets).concat(Array.prototype.slice.call(_laTargets));
                    }
                }
                for (var ti = 0; ti < targets.length; ti++) {
                    if (cssVal) {
                        targets[ti].style.fontFamily = cssVal;
                    } else {
                        targets[ti].style.fontFamily = '';
                    }
                }
            }

            
            if (elementType === 'title' && ($('#impulse-settings-body input[name="la_preset"]').val() || '')) {
                impulse_la_postUpdate();
            }
            autoSaveAndPreview();
            
            if (commit) {
                $picker.find('.impulse-font-options').hide();
                _fontPickerOpen = null;
            }
        }

        function fontPickerClose(revert) {
            if (!_fontPickerOpen) return;
            var $picker = _fontPickerOpen;
            if (revert) {
                
                var $opts = $picker.find('.impulse-font-option');
                $opts.removeClass('active');
                $picker.find('input[type="hidden"]').val(_fontPickerOriginal);
                var origLabel = 'System Default';
                _impulseFontList.forEach(function(f) { if (f.v === _fontPickerOriginal) origLabel = f.l; });
                var $trigger = $picker.find('.impulse-font-trigger');
                $trigger.find('.impulse-font-trigger-label').text(origLabel);
                $trigger.css('font-family', _fontPickerOriginal || '');
                $opts.each(function(i) { if (($(this).data('value') || '') === _fontPickerOriginal) $(this).addClass('active'); });
                
                fontPickerApply($picker, $picker.find('.impulse-font-option.active').index(), false);
            }
            $picker.find('.impulse-font-options').hide();
            _fontPickerOpen = null;
        }

        $(document).on('click', '.impulse-font-trigger', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-font-picker');
            var $opts = $picker.find('.impulse-font-options');
            var wasOpen = _fontPickerOpen && _fontPickerOpen[0] === $picker[0];
            fontPickerClose(false);
            if (!wasOpen) {
                $opts.show();
                _fontPickerOpen = $picker;
                _fontPickerOriginal = $picker.find('input[type="hidden"]').val() || '';
                
                var $all = $picker.find('.impulse-font-option');
                _fontPickerIdx = 0;
                $all.each(function(i) { if ($(this).hasClass('active')) _fontPickerIdx = i; });
            }
        });
        
        $(document).on('click', '.impulse-font-option', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-font-picker');
            var idx = $(this).index();
            fontPickerApply($picker, idx, true);
        });
        
        $(document).on('keydown', function(e) {
            if (!_fontPickerOpen) return;
            var $picker = _fontPickerOpen;
            var total = $picker.find('.impulse-font-option').length;
            if (e.key === 'ArrowDown' || e.key === 'Down') {
                e.preventDefault();
                fontPickerApply($picker, (_fontPickerIdx + 1) % total, false);
            } else if (e.key === 'ArrowUp' || e.key === 'Up') {
                e.preventDefault();
                fontPickerApply($picker, (_fontPickerIdx - 1 + total) % total, false);
            } else if (e.key === 'Enter') {
                e.preventDefault();
                fontPickerClose(false);
            } else if (e.key === 'Escape') {
                e.preventDefault();
                fontPickerClose(true);
            }
        });
        
        $(document).on('click', function(e) {
            if (_fontPickerOpen && !$(e.target).closest('.impulse-font-picker').length) {
                fontPickerClose(false);
            }
        });

        $(document).on('change', '.impulse-panel-right select', function() {

            
            autoSaveAndPreview(true);
        });

        $(document).on('change', '.impulse-panel-right input[name="tab_style"], .impulse-panel-right input[name="layout"], .impulse-panel-right input[name="source"]', function() {
            autoSaveAndRefresh();
        });

        $(document).on('change', '.impulse-panel-right input[name="auto_fit"]', function() {
            var isAutoFit = $(this).is(':checked');
            $('.impulse-auto-fit-off').toggle(!isAutoFit);
            $('.impulse-auto-fit-on').toggle(isAutoFit);
        });

        $(document).on('change', 'input[name="dt_3d_rotate"]', function() {
            $('.impulse-dt-rotate-speed').css('display', $(this).is(':checked') ? 'contents' : 'none');
        });

        

        
        
        $(document).on('change', '.impulse-panel-right input[name="show_separator"]', function() {
            $('.impulse-cd-sep-settings').toggle($(this).is(':checked'));
            autoSaveAndRefresh();
        });

        
        $(document).on('input', '.impulse-panel-right input[type="number"]', function() {
            autoSaveAndPreview();
        });

        $(document).on('input', '.impulse-panel-right input[type="range"], #impulse-screen-bar input[type="range"]', function() {
            
            if ($(this).closest('.impulse-section-anim-layer').length) return;

            var $slider = $(this);
            var $valueDisplay = $slider.closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value');
            if (!$valueDisplay.length) {
                $valueDisplay = $slider.closest('.impulse-slider-row').find('.impulse-slider-value');
            }
            if ($valueDisplay.length) {
                var unit = $slider.closest('.impulse-slider-row').data('unit') || '';
                $valueDisplay.text($slider.val() + unit);
            }

            var inputName = $(this).attr('name') || '';
            if (inputName === '_row_height' && (selectedElementType === 'rows' || selectedElementType === 'columns')) {
                var rowIndex = parseInt($slider.data('row'));
                if (!isNaN(rowIndex)) {
                    var rows = getCellGridRows();
                    if (rows[rowIndex]) {
                        rows[rowIndex].row_height = parseInt($slider.val());
                        saveCellGridRows(rows);
                    }
                    return;
                }
            }

            var inputName = $(this).attr('name') || '';
            if (inputName.startsWith('cell_') && (selectedElementType === 'rows' || selectedElementType === 'columns')) {
                
                return;
            }

            autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-richtext-buttons > button', function(e) {
            e.preventDefault();
            var cmd = $(this).data('cmd');
            if (!cmd) return;
            
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            var $editor = $wrapper.find('.impulse-richtext-editor');
            
            $editor.focus();

            var sel = window.getSelection();
            if (sel.isCollapsed && $editor[0].textContent.length > 0) {
                var range = document.createRange();
                range.selectNodeContents($editor[0]);
                sel.removeAllRanges();
                sel.addRange(range);
            }
            
            document.execCommand(cmd, false, null);

            var $hidden = $wrapper.find('input[type="hidden"]');
            $hidden.val($editor.html());

            updateRichTextToolbar($wrapper);

            autoSaveAndPreview();
        });

        

        

        

        

        

        

        

        

        

        

        

        
        var savedRichTextSelection = null;
        function _captureRichTextSelection($wrapper) {
            var $editor = $wrapper.find('.impulse-richtext-editor');
            if (!$editor.length) return;
            var sel = window.getSelection();
            if (!sel || sel.rangeCount === 0) return;
            var range = sel.getRangeAt(0);
            var editorEl = $editor[0];
            if (editorEl.contains(range.commonAncestorContainer) || editorEl === range.commonAncestorContainer) {
                savedRichTextSelection = { range: range.cloneRange(), editor: editorEl };
            }
        }
        $(document).on('mousedown', '.impulse-weight-popover', function(e) {
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            _captureRichTextSelection($wrapper);
            
            if ($(e.target).is('button') || $(e.target).closest('button').length) {
                e.preventDefault();
            }
        });

        

        $(document).on('mouseenter', '.impulse-weight-inline', function() {
            var $grp = $(this);
            var $editor = $grp.closest('.impulse-richtext-wrapper').find('.impulse-richtext-editor');
            if (!$editor.length) return;
            var fam = '';
            try { fam = window.getComputedStyle($editor[0]).fontFamily || ''; } catch (_e) {}
            $grp.find('button[data-weight]').each(function() {
                var wt = String($(this).attr('data-weight'));
                $(this).toggleClass('disabled', !_fontHasWeight(fam, wt));
            });
        });

        

        
        function _stripWeightSpans(root) {
            var spans = root.querySelectorAll('span[style*="font-weight"]');
            for (var i = spans.length - 1; i >= 0; i--) {
                var sp = spans[i];
                sp.style.fontWeight = '';
                if (!sp.getAttribute('style') || sp.getAttribute('style').replace(/;?\s*/g, '') === '') {
                    var parent = sp.parentNode;
                    while (sp.firstChild) parent.insertBefore(sp.firstChild, sp);
                    parent.removeChild(sp);
                }
            }
        }

        
        function _coalesceAdjacentWeightSpans(root) {
            var spans = root.querySelectorAll('span[style*="font-weight"]');
            for (var i = 0; i < spans.length; i++) {
                var sp = spans[i];
                var next = sp.nextSibling;
                if (next && next.nodeType === 1 && next.tagName === 'SPAN'
                    && next.style.fontWeight === sp.style.fontWeight
                    && sp.getAttribute('style') === next.getAttribute('style')) {
                    while (next.firstChild) sp.appendChild(next.firstChild);
                    next.parentNode.removeChild(next);
                }
            }
        }

        
        
        $(document).on('click', '.impulse-weight-popover button', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if ($(this).hasClass('disabled')) return; 

            var weight = $(this).data('weight');
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            var $editor = $wrapper.find('.impulse-richtext-editor');
            var $hidden = $wrapper.find('input[type="hidden"]');
            var editorEl = $editor[0];

            if (weight === 'reset') {
                _stripWeightSpans(editorEl);
                $hidden.val($editor.html());
                savedRichTextSelection = null;
                autoSaveAndPreview(true);
                return;
            }

            

            

            
            
            _stripWeightSpans(editorEl);
            var content = $editor.html();
            if (content) {
                $editor.html('<span style="font-weight:' + weight + '">' + content + '</span>');
            }

            $hidden.val($editor.html());
            savedRichTextSelection = null;

            
            var $inlineGrp = $(this).closest('.impulse-weight-inline');
            if ($inlineGrp.length) {
                $inlineGrp.find('button').removeClass('active');
                $(this).addClass('active');
            }
            autoSaveAndPreview(true);
        });

        $(document).on('input', '.impulse-richtext-editor', function() {
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            var $hidden = $wrapper.find('input[type="hidden"]');
            var content = $(this).html();

            if (content === 'Add your text content here.' || content.indexOf('Add your text') === 0) {
                $(this).html('');
                content = '';
            }
            
            $hidden.val(content);
            
            $wrapper.find('.impulse-richtext-html').val(content);
            autoSaveAndPreview();
        });

        $(document).on('input', '.impulse-richtext-html', function() {
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            var $hidden = $wrapper.find('input[type="hidden"]');
            var content = $(this).val();
            
            $hidden.val(content);
            
            $wrapper.find('.impulse-richtext-editor').html(impulseMarkdownToHtml(content));
            autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-richtext-tab', function() {
            var mode = $(this).data('mode');
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            var $visual = $wrapper.find('.impulse-richtext-editor');
            var $html = $wrapper.find('.impulse-richtext-html');
            var $buttons = $wrapper.find('.impulse-richtext-buttons');

            $wrapper.find('.impulse-richtext-tab').removeClass('active');
            $(this).addClass('active');
            
            if (mode === 'html') {
                
                $html.val($visual.html()).show();
                $visual.hide();
                $buttons.hide();
            } else {
                
                $visual.html($html.val()).show();
                $html.hide();
                $buttons.show();
            }
        });

        $(document).on('keyup mouseup', '.impulse-richtext-editor', function() {
            var $wrapper = $(this).closest('.impulse-richtext-wrapper');
            updateRichTextToolbar($wrapper);
        });
        
        function updateRichTextToolbar($wrapper) {
            var $toolbar = $wrapper.find('.impulse-richtext-toolbar');
            $toolbar.find('button[data-cmd]').each(function() {
                var cmd = $(this).data('cmd');
                if (cmd) {
                    $(this).toggleClass('active', document.queryCommandState(cmd));
                }
            });
        }

        $(document).on('keydown', '.impulse-richtext-editor', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                
                e.stopPropagation();
            }
        });

        $(document).on('paste', '.impulse-richtext-editor', function(e) {
            e.preventDefault();
            var text = '';
            if (e.originalEvent && e.originalEvent.clipboardData) {
                text = e.originalEvent.clipboardData.getData('text/plain');
            } else if (window.clipboardData) {
                text = window.clipboardData.getData('Text');
            }
            if (!text) return;
            
            document.execCommand('insertText', false, text);
        });

        

        
        window.impulseCSSVars = {
            
            units: {
                
                size: 'px', font_size: 'px', width: '%', height: 'px',
                min_width: 'px', max_width: 'px', min_height: 'px', max_height: 'px',
                icon_size: 'px', image_size: 'px', avatar_size: 'px',
                title_size: 'px', text_size: 'px', subtitle_size: 'px',
                content_size: 'px', label_size: 'px', price_size: 'px', number_size: 'px',
                preview_max_width: 'px',
                pl_title_size: 'px', pl_price_size: 'px', pl_desc_size: 'px', pl_spacing: 'px', pl_icon_size: 'px',
                element_icon_size: 'px', element_text_size: 'px',
                front_title_size: 'px', front_content_size: 'px',
                back_title_size: 'px', back_content_size: 'px',
                button_size: 'px', button_font_size: 'px', menu_font_size: 'px',

                gap: 'px', row_gap: 'px', column_gap: 'px',
                padding: 'px', padding_top: 'px', padding_right: 'px',
                padding_bottom: 'px', padding_left: 'px',
                padding_x: 'px', padding_y: 'px',
                margin: 'px', margin_top: 'px', margin_right: 'px',
                margin_bottom: 'px', margin_left: 'px',
                spacing: 'px', element_spacing: 'px', text_spacing: 'px',
                icon_spacing: 'px', icon_padding: 'px', icon_gap: 'px',
                cell_gap: 'px', item_gap: 'px', menu_gap: 'px', item_space: 'px',
                cell_padding_h: 'px', cell_padding_v: 'px',
                button_padding: 'px', content_padding: 'px', box_padding: 'px', inner_padding: 'px',
                min_height: 'px', content_width: '%', max_content_width: 'px',

                border_width: 'px', border_radius: 'px', radius: 'px',
                thickness: 'px', icon_border_width: 'px', icon_radius: 'px',
                field_border_width: 'px', field_radius: 'px',
                button_radius: 'px', card_radius: 'px', cell_radius: 'px',
                cell_border_width: 'px',
                popup_width: 'px', popup_height: 'px', popup_padding: 'px', popup_radius: 'px',
                section_max_width: 'px',
                btn_height: 'px',

                

                

                
                
                btn_min_width: 'px',

                cell_padding_top: 'px', cell_padding_bottom: 'px', cell_padding_sides: 'px',
                padding_sides: 'px', col_gap: 'px',
                gap_horizontal: 'px', gap_vertical: 'px',

                line_height: '', letter_spacing: 'px',

                animation_duration: 'ms', animation_delay: 'ms',
                transition_speed: 'ms', hover_transition: 'ms', hh_duration: 'ms',

                border_gradient_angle: 'deg', border_mouse_sens: '', border_spin_speed: '',

                opacity: '', overlay_opacity: '', zoom: '', zoom_scale: '',
                
                depth_parallax_intensity: '',
                
                depth: '', dof_intensity: '', perspective: 'px'
            },

            getDoc: function() {
                var iframe = document.getElementById('impulse-iframe');
                return iframe && iframe.contentDocument ? iframe.contentDocument : null;
            },

            apply: function(elementId, settings) {
                var doc = this.getDoc();
                if (!doc) return false;
                
                var el = doc.querySelector('.impulse-el[data-id="' + elementId + '"]');
                if (!el) return false;
                
                if (el.dataset.type === 'grid') {
                }

                var justifyMap = { left: 'flex-start', center: 'center', right: 'flex-end' };
                
                for (var key in settings) {
                    var value = settings[key];
                    if (value === undefined || value === null || value === '') continue;

                    if (key.indexOf('_id') !== -1 || key === 'type' || key === 'id') continue;
                    
                    if (key === 'align') continue;

                    var varName = '--impulse-' + key.replace(/_/g, '-');

                    

                    
                    
                    if (key === 'border_gradient_angle') {
                        varName = '--impulse-border-gradient-angle-base';
                    }

                    

                    if ((key === 'font_size' || key === 'size' || key === 'text_size' || key === 'title_size' || key === 'subtitle_size' || key === 'label_size' || key === 'number_size' || key === 'button_font_size' || key === 'max_width') && (value === 0 || value === '0')) {
                        el.style.removeProperty(varName);
                        continue;
                    }

                    

                    if (key === 'btn_min_width' && (value === 0 || value === '0')) {
                        el.style.removeProperty(varName);
                        continue;
                    }

                    var unit = this.units[key] || '';
                    var cssValue;
                    
                    if (key === 'line_height') {
                        cssValue = (parseFloat(value) / 100);
                    } else {
                        cssValue = (typeof value === 'number' || !isNaN(value)) && unit ? value + unit : value;
                    }
                    
                    el.style.setProperty(varName, cssValue);

                    
                    
                    if (key === 'align' && justifyMap[value]) {
                        el.style.setProperty('--impulse-justify', justifyMap[value]);
                    }
                }
                
                if (el.dataset.type === 'grid') {
                }
                return true;
            },

            migratedBlocks: ['divider', 'text', 'button', 'image', 'icon', 'video', 'social', 'section', 'table', 'title', 'map', 'price_list', 'carousel', 'grid', 'rows', 'columns', 'shortcode', 'unfold', 'plans', 'animator', 'flip_box', 'contact', 'login', 'register', 'booking', 'products', 'bundle', 'header', 'footer', 'cart', 'order_summary', 'receipt', 'account', 'checkout', 'slider', 'icon_text', 'product_carousel', 'popup', 'modal', 'shipping']
        };

        

        

        window.IMPULSE_PAGE_AUTO_SCALE = function(resolved, base, device) {
            if (device === 'desktop' || !resolved || !base) return resolved;
            var factors = {
                padding_top:     { tablet: 0.80, mobile: 0.60 },
                padding_bottom:  { tablet: 0.80, mobile: 0.60 },
                padding_left:    { tablet: 0.70, mobile: 0.50 },
                padding_right:   { tablet: 0.70, mobile: 0.50 },
                element_spacing: { tablet: 0.80, mobile: 0.55 }
            };
            for (var k in factors) {
                var overrideKey = k + '_' + device;
                if (base[overrideKey] !== undefined && base[overrideKey] !== '' && base[overrideKey] !== null) continue;
                var dv = parseFloat(base[k]);
                if (isNaN(dv) || dv <= 0) continue;
                resolved[k] = Math.round(dv * factors[k][device]);
            }
            return resolved;
        };

        function resolveDeviceSettings(settings, device) {
            if (device === 'desktop') return settings;
            
            var resolved = $.extend({}, settings);
            var responsiveSettings = window.RESPONSIVE_SETTINGS || [];
            
            for (var i = 0; i < responsiveSettings.length; i++) {
                var key = responsiveSettings[i];
                
                if (device === 'mobile') {
                    
                    if (settings[key + '_mobile'] !== undefined) {
                        resolved[key] = settings[key + '_mobile'];
                    } else if (settings[key + '_tablet'] !== undefined) {
                        resolved[key] = settings[key + '_tablet'];
                    }
                } else {
                    
                    if (settings[key + '_tablet'] !== undefined) {
                        resolved[key] = settings[key + '_tablet'];
                    }
                }
            }
            
            return resolved;
        }

        function autoMobileDefaults(settings, elementType, device) {
            if (device === 'desktop') return settings;
            var isTablet = device === 'tablet';
            var suffix = '_' + device;
            var s = $.extend({}, settings);

            function scale(key, t, m) {
                if (s[key + suffix] !== undefined) return; 
                var base = parseFloat(s[key]);
                if (isNaN(base)) return;
                var result = Math.round(base * (isTablet ? t : m));
                s[key + suffix] = result;

            }

            
            
            if (elementType === 'title') {
                scale('line_1_size',  0.80, 0.62);
                if (parseFloat(s.letter_spacing) > 0) scale('letter_spacing', 0.70, 0.50);
                scale('line_1_depth', 0.70, 0.35);
                scale('mouse_sens',   0.60, 0.00);
                scale('orbit_speed',  0.60, 0.00);
                scale('la_font_size',   0.80, 0.62);
                scale('la_image_width', 0.80, 0.65);
                if (parseFloat(s.la_gap_below) > 0) scale('la_gap_below', 0.75, 0.50);
            }
            return s;
        }

        

        

        

        

        

        

        function _liveIsHandledByCss(settingDef) {
            if (!settingDef) return false;                            
            if (settingDef.render_type === 'refresh') return false;   
            if (settingDef.render_type === 'none')    return true;    
            if (settingDef.selector) return true;                     
            if (settingDef.render_type === 'css_var') return true;
            if (settingDef.render_type === 'content') return true;
            return false;
        }
        
        var _liveIgnoreKeys = {
            _selected_cells: 1, _cell_row: 1, _cell_col: 1,
            _row_height: 1
        };

        

        

        

        

        var _liveTypeFallbackHandled = {
            button: {
                border_radius: 1, border_gradient_angle: 1,
                border_mouse_sens: 1, border_spin_speed: 1, border_color: 1,
                border_width: 1,

                

                
                bg_color: 1,
                frosted_glass: 1
            },

            

            
            text: {
                color: 1,
                text_gradient_to: 1,
                text_gradient_angle: 1,
                text_mouse_sens: 1,
                text_spin_speed: 1
            },

            

            

            

            section: {
                bg_color: 1, bg_color_2: 1, bg_color_3: 1, bg_color_4: 1,
                bg_mesh_speed: 1, bg_mesh_grain: 1, bg_mesh_mouse_sens: 1,
                bg_mesh_distort: 1, bg_mesh_distort_edges: 1,
                bg_mesh_outer_padding: 1,
                
                bg_mesh_alpha: 1, mesh_base_color: 1,
                bg_color_x: 1, bg_color_y: 1,
                bg_color_2_x: 1, bg_color_2_y: 1,
                bg_color_3_x: 1, bg_color_3_y: 1,
                bg_color_4_x: 1, bg_color_4_y: 1,
                gradient_overlay_color1: 1, gradient_overlay_color2: 1,
                gradient_overlay_diameter: 1, gradient_overlay_roundness: 1,
                gradient_overlay_angle: 1, gradient_overlay_softness: 1,
                gradient_overlay_type: 1,

                

                
                
                bg_parallax_sens: 1,

                

                bg_depth_strength: 1,
                
                screen_autoplay_seconds: 1,
                _screen_autoplay_on_ui: 1,
                
                screen_min_height_vh: 1,
                
                ovfx: 1, ovfx_ease: 1, ovfx_speed: 1,
                ovfx_p1: 1, ovfx_p2: 1, ovfx_p3: 1,
                ovfx_c1: 1, ovfx_c2: 1
            },
            
            kinetic: {
                composition: 1, text: 1, tier: 1, line_gap: 1, max_width: 1, cyl_diameter: 1, accent: 1, accent_text: 1,
                
                cl_color_0: 1, cl_color_1: 1, cl_color_2: 1, cl_color_3: 1,
                color: 1, loop: 1, speed: 1, intensity: 1, height: 1,
                custom_mode: 1, custom_lines: 1, fit_container: 1, scroll_exit: 1, lead_screen: 1, height_auto: 1, height_mode: 1, cycle: 1,
                
                grad_mode: 1, grad_scope: 1, grad_c1: 1, grad_c2: 1,
                
                preset: 1, align: 1, font: 1, weight: 1, fill: 1,
                phrases: 1, raw_text: 1
            }
        };
        function _liveAnyUnhandledChange(elType, settings, prevSettings) {
            var elConfig = (window.ImpulseElementConfig && window.ImpulseElementConfig.get)
                ? window.ImpulseElementConfig.get(elType) : null;
            var configSettings = elConfig ? (elConfig.settings || {}) : {};
            var fallback = _liveTypeFallbackHandled[elType] || {};

            

            

            
            
            var _laHeadingActive = (elType === 'title' && settings.la_preset);
            for (var key in settings) {
                if (!Object.prototype.hasOwnProperty.call(settings, key)) continue;
                if (_liveIgnoreKeys[key]) continue;
                if (_laHeadingActive && (
                    key.indexOf('la_') === 0 ||
                    key === 'line_1' || key === 'line_1_color' ||
                    key === 'line_1_size' || key === 'line_1_weight' ||
                    key === 'line_1_font' || key === 'line_1_fill' ||
                    key === 'line_1_grad_1' || key === 'line_1_grad_2' || key === 'line_1_grad_angle' ||
                    key === 'font_family' || key === 'letter_spacing' || key === 'margin_bottom' ||
                    key === 'align' || key === 'mouse_sens'
                )) continue;
                
                var baseKey = key.replace(/_(?:tablet|mobile)$/, '');
                var prevVal = prevSettings ? prevSettings[key] : undefined;
                var curVal  = settings[key];
                if (prevVal === curVal) continue;
                
                if (typeof curVal === 'object' || typeof prevVal === 'object') {
                    try {
                        if (JSON.stringify(prevVal) === JSON.stringify(curVal)) continue;
                    } catch (_e) {}
                }

                if (_liveIsHandledByCss(configSettings[baseKey])) continue;
                if (fallback[baseKey]) continue;
                if (window.impulseDebug) {
                    console.log('[live-refresh] unregistered change:', elType, baseKey,
                        'prev:', prevVal, 'cur:', curVal);
                }
                return true;
            }
            return false;
        }

        

        
        
        function _impulseColorToRgba(color, alpha) {
            color = String(color || '').trim();
            if (!color || color === 'transparent') return 'rgba(255,255,255,' + alpha + ')';
            var m = color.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+\s*)?\)$/i);
            if (m) return 'rgba(' + (+m[1]) + ',' + (+m[2]) + ',' + (+m[3]) + ',' + alpha + ')';
            var h = color.match(/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
            if (h) {
                var hex = h[1];
                var r, g, b;
                if (hex.length === 3) {
                    r = parseInt(hex[0] + hex[0], 16);
                    g = parseInt(hex[1] + hex[1], 16);
                    b = parseInt(hex[2] + hex[2], 16);
                } else {
                    r = parseInt(hex.substr(0,2), 16);
                    g = parseInt(hex.substr(2,2), 16);
                    b = parseInt(hex.substr(4,2), 16);
                }
                return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
            }
            
            return 'rgba(255,255,255,' + alpha + ')';
        }

        function livePreviewSettings() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            if ($('#impulse-settings-body').text().indexOf('Loading') !== -1) return;

            var settings = collectSettingsFromPanel();
            var type = $('.impulse-panel-right').data('element-type') || selectedElementType;
            var device = window.impulseDevice || 'desktop';

            

            

            
            
            if (type === 'button') {
                var _btnFP_resolved = (function() {
                    var _r = $.extend({}, settings);
                    if (device !== 'desktop') {
                        var _resp = window.RESPONSIVE_SETTINGS || [];
                        for (var i = 0; i < _resp.length; i++) {
                            var k = _resp[i];
                            var dk = k + '_' + device;
                            if (settings[dk] !== undefined) _r[k] = settings[dk];
                        }
                    }
                    return _r;
                })();
                var _btnFP_doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
                if (window.impulseDebug) {
                    console.log('[btn-fastpath] id=', id, 'doc=', !!_btnFP_doc,
                        'border_radius=', _btnFP_resolved.border_radius,
                        'border_spin_speed=', _btnFP_resolved.border_spin_speed);
                }
                if (_btnFP_doc) {
                    var _btnFP_a = _btnFP_doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-button');
                    if (_btnFP_a) {
                        var _btnFP_rad = parseInt(_btnFP_resolved.border_radius);
                        if (!isNaN(_btnFP_rad)) _btnFP_a.style.borderRadius = _btnFP_rad + 'px';
                        if (_btnFP_resolved.border_gradient_to !== undefined) {
                            _btnFP_a.style.setProperty('--impulse-border-gradient-to',
                                _btnFP_resolved.border_gradient_to || 'transparent');
                        }
                        if (_btnFP_resolved.border_color !== undefined) {
                            _btnFP_a.style.setProperty('--impulse-border-color',
                                _btnFP_resolved.border_color || '#1d2327');
                        }
                        if (_btnFP_resolved.border_gradient_angle !== undefined) {
                            var _btnFP_ang = parseInt(_btnFP_resolved.border_gradient_angle);
                            if (!isNaN(_btnFP_ang)) _btnFP_a.style.setProperty(
                                '--impulse-border-gradient-angle-base', _btnFP_ang + 'deg');
                        }
                        if (_btnFP_resolved.border_mouse_sens !== undefined) {
                            var _btnFP_ms = parseInt(_btnFP_resolved.border_mouse_sens);
                            _btnFP_a.style.setProperty('--impulse-border-mouse-sens',
                                String(isNaN(_btnFP_ms) ? 0 : _btnFP_ms));
                            _btnFP_a.dataset.borderGradMouse = String(isNaN(_btnFP_ms) ? 0 : _btnFP_ms);
                        }
                        if (_btnFP_resolved.border_spin_speed !== undefined) {
                            var _btnFP_sp = parseInt(_btnFP_resolved.border_spin_speed);
                            _btnFP_a.style.setProperty('--impulse-border-spin-speed',
                                String(isNaN(_btnFP_sp) ? 0 : _btnFP_sp));
                            _btnFP_a.dataset.borderGradSpin = String(isNaN(_btnFP_sp) ? 0 : _btnFP_sp);
                        }
                        if (_btnFP_resolved.border_width !== undefined) {
                            var _btnFP_bw = parseInt(_btnFP_resolved.border_width);
                            if (!isNaN(_btnFP_bw)) {
                                _btnFP_a.style.borderWidth = _btnFP_bw + 'px';

                                
                                _btnFP_a.style.setProperty('--impulse-border-width', _btnFP_bw + 'px');
                            }
                        }

                        

                        

                        

                        

                        

                        

                        if (_btnFP_resolved.btn_min_width !== undefined) {
                            var _btnFP_mw = parseInt(_btnFP_resolved.btn_min_width);
                            var _btnFP_wrap = _btnFP_a.parentElement; 
                            if (!isNaN(_btnFP_mw) && _btnFP_mw > 0) {
                                _btnFP_a.style.width = _btnFP_mw + 'px';
                                _btnFP_a.style.maxWidth = 'none';
                                if (_btnFP_wrap) {
                                    _btnFP_wrap.style.maxWidth = 'none';
                                    _btnFP_wrap.style.overflow = 'visible';
                                }
                            } else {
                                _btnFP_a.style.width = '';
                                _btnFP_a.style.maxWidth = '';
                                if (_btnFP_wrap) {
                                    _btnFP_wrap.style.maxWidth = '';
                                    _btnFP_wrap.style.overflow = '';
                                }
                            }
                        }

                        

                        

                        var _btnFP_frost = !!_btnFP_resolved.frosted_glass;
                        var _btnFP_bg = (_btnFP_resolved.bg_color !== undefined && _btnFP_resolved.bg_color !== '')
                            ? String(_btnFP_resolved.bg_color) : '';
                        if (_btnFP_frost) {

                            

                            

                            
                            
                            _btnFP_a.style.setProperty('background', 'rgba(255,255,255,0.18)', 'important');
                            _btnFP_a.style.setProperty('--impulse-bg-color', 'rgba(255,255,255,0.18)');
                            _btnFP_a.style.setProperty('--impulse-border-color', '#1c2226');
                            _btnFP_a.style.setProperty('--impulse-border-gradient-to', 'rgba(247,247,247,0.57)');
                            _btnFP_a.style.setProperty('--impulse-border-gradient-angle-base', '135deg');
                            _btnFP_a.style.setProperty('--impulse-border-mouse-sens', '100');
                            _btnFP_a.style.setProperty('--impulse-border-spin-speed', '90');
                            _btnFP_a.style.setProperty('--impulse-border-width', '1px');
                            _btnFP_a.style.setProperty('border', '1px solid transparent');
                            _btnFP_a.style.setProperty('box-sizing', 'border-box');
                            _btnFP_a.style.setProperty('isolation', 'isolate');
                            _btnFP_a.style.setProperty('backdrop-filter', 'blur(20px) saturate(180%) brightness(1.15)');
                            _btnFP_a.style.setProperty('-webkit-backdrop-filter', 'blur(20px) saturate(180%) brightness(1.15)');
                            _btnFP_a.dataset.borderGradMouse = '100';
                            _btnFP_a.dataset.borderGradBase  = '135';
                            _btnFP_a.dataset.borderGradSpin  = '90';
                            _btnFP_a.classList.add('impulse-frosted');
                            _btnFP_a.classList.add('impulse-grad-border');
                        } else {
                            _btnFP_a.style.removeProperty('backdrop-filter');
                            _btnFP_a.style.removeProperty('-webkit-backdrop-filter');
                            _btnFP_a.classList.remove('impulse-frosted');
                            _btnFP_a.style.removeProperty('--impulse-text-color');

                            

                            

                            

                            
                            _btnFP_a.style.removeProperty('background');
                            if (_btnFP_bg) {
                                _btnFP_a.style.setProperty('--impulse-bg-color', _btnFP_bg);
                            }
                            var _btnFP_bgFallback = _btnFP_bg || 'transparent';
                            _btnFP_a.style.setProperty('background',
                                'var(--impulse-bg-color, ' + _btnFP_bgFallback + ')',
                                'important');
                        }
                    }
                }
            }

            

            

            

            
            window._impulsePrevAllSettings = window._impulsePrevAllSettings || {};
            var _liveExempt = (type === 'title' || type === 'chart' || type === 'rows' || type === 'columns');
            if (!_liveExempt) {
                var _livePrevAll = window._impulsePrevAllSettings[id];
                var _liveNeedsRefresh = _livePrevAll
                    ? _liveAnyUnhandledChange(type, settings, _livePrevAll)
                    : false;
                window._impulsePrevAllSettings[id] = JSON.parse(JSON.stringify(settings));
                if (_liveNeedsRefresh) return 'needs-refresh';
            }

            

            

            

            

            

            

            if (type === 'title' && settings.la_preset) return;

            
            
            if (type === 'chart') return 'needs-refresh';

            if (type === 'products' || type === 'products') {
                postModalStylesToIframe();
            }

            var resolvedSettings = resolveDeviceSettings(settings, device);

            var entranceKeys = ['entrance_animation','entrance_intensity','animation_duration','unveil_direction'];
            function stripEntrance(obj) {
                var copy = {};
                for (var k in obj) {
                    if (entranceKeys.indexOf(k) === -1) copy[k] = obj[k];
                }
                return copy;
            }

            if (window.impulseCSSVars.migratedBlocks.indexOf(type) !== -1) {
                if (type === 'section') {

                    

                    var _hmLive = resolvedSettings.height_mode || '';
                    var _mhLive = resolvedSettings.min_height;
                    if (_hmLive === '' && _mhLive != null && _mhLive !== '' && _mhLive !== 0) {
                        _hmLive = 'vh'; 
                    }
                    var _docLive = window.impulseCSSVars.getDoc();
                    if (_docLive) {
                        var _secLiveEl = _docLive.querySelector('.impulse-el[data-id="' + id + '"]');
                        if (_secLiveEl) {
                            if (_hmLive === 'vh' && parseInt(_mhLive || 0, 10) > 0) {
                                _secLiveEl.style.setProperty('--impulse-min-height', Math.min(100, parseInt(_mhLive, 10)) + 'vh');
                            } else if (_hmLive === 'px') {
                                var _pxLive = Math.max(0, Math.min(2000, parseInt(resolvedSettings.height_px || 0, 10)));
                                if (_pxLive > 0) _secLiveEl.style.setProperty('--impulse-min-height', _pxLive + 'px');
                                else             _secLiveEl.style.removeProperty('--impulse-min-height');
                            } else {

                                _secLiveEl.style.removeProperty('--impulse-min-height');
                            }
                        }
                    }

                    var sectionCSSKeys = ['padding_top','padding_bottom','padding_left','padding_right','item_space'];
                    var filtered = {};
                    for (var si = 0; si < sectionCSSKeys.length; si++) {
                        var sk = sectionCSSKeys[si];
                        if (resolvedSettings[sk] !== undefined) filtered[sk] = resolvedSettings[sk];
                    }
                    window.impulseCSSVars.apply(id, filtered);

                    
                    if (resolvedSettings.content_width !== undefined) {
                        var _docCW = window.impulseCSSVars.getDoc();
                        if (_docCW) {
                            var _containerCW = _docCW.querySelector('.impulse-el[data-id="' + id + '"] > .impulse-section > .impulse-container');
                            if (_containerCW) {
                                var _cwVal = parseInt(resolvedSettings.content_width);
                                if (!isNaN(_cwVal)) _containerCW.style.width = _cwVal + '%';
                            }
                        }
                    }

                    var doc2 = window.impulseCSSVars.getDoc();
                    if (doc2) {
                        var sectionEl = doc2.querySelector('.impulse-el[data-id="' + id + '"] > .impulse-section');
                        if (sectionEl) {

                            

                            

                            
                            
                            if (typeof resolvedSettings.bg_color === 'string' && resolvedSettings.bg_color !== '') {
                                var newBgColor = resolvedSettings.bg_color;
                                if (newBgColor === 'transparent') {
                                    sectionEl.style.removeProperty('--impulse-bg-color');
                                } else {
                                    sectionEl.style.setProperty('--impulse-bg-color', newBgColor);
                                }
                            }

                            

                            

                            

                            
                            
                            if (typeof resolvedSettings.bg_image === 'string' && resolvedSettings.bg_image !== '') {
                                sectionEl.style.backgroundImage = 'url(' + resolvedSettings.bg_image + ')';
                                sectionEl.style.backgroundSize = resolvedSettings.bg_size || 'cover';
                                sectionEl.style.backgroundPosition = resolvedSettings.bg_position || 'center';
                                sectionEl.style.backgroundRepeat = 'no-repeat';
                            }

                            

                            var newOverlayOpacity = resolvedSettings.overlay_opacity !== undefined ? resolvedSettings.overlay_opacity / 100 : 0;
                            var overlayEl = sectionEl.querySelector('.impulse-section-overlay');
                            if (newOverlayOpacity > 0) {
                                var newOverlayColor = resolvedSettings.overlay_color || 'transparent';
                                if (!overlayEl) {
                                    overlayEl = doc2.createElement('div');
                                    overlayEl.className = 'impulse-section-overlay';
                                    overlayEl.style.cssText = 'position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none;z-index:1';
                                    sectionEl.appendChild(overlayEl);
                                }
                                overlayEl.style.backgroundColor = newOverlayColor;
                                overlayEl.style.opacity = newOverlayOpacity;
                            } else if (overlayEl) {
                                overlayEl.parentNode.removeChild(overlayEl);
                            }

                            

                            
                            var _goC1 = resolvedSettings.gradient_overlay_color1 || 'rgba(0,0,0,0)';
                            var _goC2 = resolvedSettings.gradient_overlay_color2 || 'rgba(0,0,0,0)';
                            var _goAlive = function (c) {
                                if (!c || c === 'transparent') return false;
                                if (c.indexOf('rgba(0,0,0,0)') === 0) return false;
                                var m = c.match(/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([\d.]+))?\s*\)/i);
                                if (m && m[1] !== undefined && m[1] !== '') return parseFloat(m[1]) > 0.02;
                                return true;
                            };
                            var _goActive = _goAlive(_goC1) || _goAlive(_goC2);
                            var _goEl = sectionEl.querySelector(':scope > .impulse-gradient-overlay');
                            if (!_goActive) {
                                if (_goEl) _goEl.remove();
                            } else {
                                if (!_goEl) {
                                    _goEl = doc2.createElement('div');
                                    _goEl.className = 'impulse-gradient-overlay';
                                    _goEl.style.cssText = 'position:absolute;inset:0;pointer-events:none;z-index:2;overflow:hidden;border-radius:inherit';
                                    _goEl.innerHTML = '<div class="impulse-gradient-overlay-inner"></div>';
                                    sectionEl.appendChild(_goEl);
                                }
                                var _goType = (resolvedSettings.gradient_overlay_type === 'linear') ? 'linear' : 'radial';
                                var _goD  = Math.max(10, Math.min(200, parseInt(resolvedSettings.gradient_overlay_diameter)  || 100));
                                var _goAg = (((parseInt(resolvedSettings.gradient_overlay_angle) || 0) % 360) + 360) % 360;
                                var _goSf = Math.max(0, Math.min(100, parseInt(resolvedSettings.gradient_overlay_softness) || 0));
                                var _goInnerEl = _goEl.querySelector('.impulse-gradient-overlay-inner');
                                if (_goInnerEl) {
                                    if (_goType === 'linear') {

                                        
                                        var _reach = Math.max(5, Math.min(100, _goD / 2));
                                        var _c1End = Math.max(0, _reach * (1 - _goSf / 100));
                                        _goInnerEl.style.cssText =
                                            'position:absolute;inset:0;' +
                                            'background:linear-gradient(' + _goAg + 'deg,' +
                                                _goC1 + ' 0%,' + _goC1 + ' ' + _c1End.toFixed(2) + '%,' +
                                                _goC2 + ' ' + _reach.toFixed(2) + '%,' + _goC2 + ' 100%);';
                                    } else {
                                        var _goR  = Math.max(0,  Math.min(100, parseInt(resolvedSettings.gradient_overlay_roundness) || 100));
                                        var _goRX = _goD / 2;
                                        var _goRY = Math.max(0.5, _goRX * (_goR / 100));
                                        var _goInner = Math.max(0,   (100 - _goSf) / 2);
                                        var _goOuter = Math.min(100, 100 - _goInner);
                                        _goInnerEl.style.cssText =
                                            'position:absolute;top:50%;left:50%;width:200%;height:200%;' +
                                            'background:radial-gradient(ellipse ' + _goRX.toFixed(2) + '% ' + _goRY.toFixed(2) + '% at center,' +
                                                _goC1 + ' 0%,' + _goC1 + ' ' + _goInner.toFixed(2) + '%,' +
                                                _goC2 + ' ' + _goOuter.toFixed(2) + '%,' + _goC2 + ' 100%);' +
                                            'transform:translate(-50%,-50%) rotate(' + _goAg + 'deg);';
                                    }
                                }
                            }
                        }
                    }
                } else if (type === 'unfold') {

                    

                    
                    var _ufDoc = window.impulseCSSVars.getDoc();
                    var _ufWrap = _ufDoc && _ufDoc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-unfold');
                    if (_ufWrap) {
                        var _ufColor = function (v, val) { if (val !== undefined && val !== null && val !== '') _ufWrap.style.setProperty(v, val); };
                        var _ufPx = function (v, key) { var n = parseInt(resolvedSettings[key]); if (!isNaN(n)) _ufWrap.style.setProperty(v, n + 'px'); };
                        _ufColor('--unf-title',      resolvedSettings.header_color);
                        _ufColor('--unf-content-bg', resolvedSettings.content_bg);
                        _ufColor('--unf-content',    resolvedSettings.content_color);
                        _ufColor('--unf-accent',     resolvedSettings.accent_color);
                        _ufColor('--unf-border',     resolvedSettings.border_color);
                        _ufPx('--unf-radius',   'border_radius');
                        _ufPx('--unf-pad',      'content_padding');
                        _ufPx('--unf-row-pad',  'row_padding');
                        _ufPx('--unf-t-size',   'title_size');
                        _ufPx('--unf-c-size',   'content_size');
                        _ufPx('--unf-n-size',   'number_size');

                        var _ufCh = parseInt(resolvedSettings.card_height);
                        if (!isNaN(_ufCh) && _ufCh > 0) {
                            _ufWrap.style.setProperty('--unf-tile-h', _ufCh + 'px');
                            _ufWrap.style.setProperty('--unf-card-h', _ufCh + 'px');
                        }
                    }
                    window.impulseCSSVars.apply(id, resolvedSettings);
                } else {
                    window.impulseCSSVars.apply(id, resolvedSettings);
                }
            }

            

            

            
            if (type === 'text') {

                

                
                
                var _contentKey = (device === 'mobile' && settings.content_mobile !== undefined) ? 'content_mobile'
                                : (device === 'tablet' && settings.content_tablet !== undefined) ? 'content_tablet'
                                : (device === 'mobile' && settings.content_tablet !== undefined) ? 'content_tablet'
                                : 'content';
                if (settings[_contentKey] !== undefined) {
                    var doc = window.impulseCSSVars.getDoc();
                    if (doc) {
                        var ceEl = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-text [contenteditable]');
                        if (ceEl) {
                            var _rawContent = settings[_contentKey] || '';
                            var _newHtml = impulseMarkdownToHtml(_rawContent);

                            

                            

                            
                            
                            var _isFocused = (typeof doc.hasFocus === 'function' ? doc.hasFocus() : true)
                                && (doc.activeElement === ceEl || ceEl.contains(doc.activeElement));
                            if (!_isFocused && ceEl.innerHTML !== _newHtml) {
                                ceEl.innerHTML = _newHtml;
                            }
                            var txt = ceEl.innerText.trim();
                            if (!txt) {
                                ceEl.classList.add('is-empty');
                            } else {
                                ceEl.classList.remove('is-empty');
                            }
                        }
                    }
                }
            }

            

            

            

            

            

            
            if (type === 'button') {
                var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
                if (window.impulseDebug) {
                    console.log('[btn-live] type=button, doc=', !!doc,
                        'border_radius=', resolvedSettings.border_radius,
                        'border_gradient_to=', resolvedSettings.border_gradient_to,
                        'border_spin_speed=', resolvedSettings.border_spin_speed);
                }
                if (doc) {
                    var btnA = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-button');
                    if (window.impulseDebug) console.log('[btn-live] btnA found:', !!btnA, 'id=', id);
                    if (btnA) {

                        

                        

                        
                        
                        var _hadGrad = btnA.classList.contains('impulse-grad-border');
                        var _isOff   = function(v) { return !v || v === 'transparent' || v.indexOf('rgba(0,0,0,0)') === 0; };
                        var _hasGrad = !_isOff(String(resolvedSettings.border_gradient_to || '').trim());
                        if (_hadGrad !== _hasGrad) return 'needs-refresh';

                        var rad = parseInt(resolvedSettings.border_radius);
                        if (!isNaN(rad)) {
                            btnA.style.borderRadius = rad + 'px';
                        }

                        
                        
                        if (resolvedSettings.border_gradient_to !== undefined) {
                            btnA.style.setProperty('--impulse-border-gradient-to',
                                resolvedSettings.border_gradient_to || 'transparent');
                        }
                        if (resolvedSettings.border_color !== undefined) {
                            btnA.style.setProperty('--impulse-border-color',
                                resolvedSettings.border_color || '#1d2327');
                        }
                        if (resolvedSettings.border_gradient_angle !== undefined) {
                            var ang = parseInt(resolvedSettings.border_gradient_angle);
                            if (!isNaN(ang)) btnA.style.setProperty(
                                '--impulse-border-gradient-angle-base', ang + 'deg');
                        }
                        if (resolvedSettings.border_mouse_sens !== undefined) {
                            var ms = parseInt(resolvedSettings.border_mouse_sens);
                            btnA.style.setProperty('--impulse-border-mouse-sens',
                                String(isNaN(ms) ? 0 : ms));

                            btnA.dataset.borderGradMouse = String(isNaN(ms) ? 0 : ms);
                        }
                        if (resolvedSettings.border_spin_speed !== undefined) {
                            var sp = parseInt(resolvedSettings.border_spin_speed);
                            btnA.style.setProperty('--impulse-border-spin-speed',
                                String(isNaN(sp) ? 0 : sp));
                            btnA.dataset.borderGradSpin = String(isNaN(sp) ? 0 : sp);
                        }
                        if (resolvedSettings.border_width !== undefined) {
                            var bw = parseInt(resolvedSettings.border_width);
                            if (!isNaN(bw)) btnA.style.borderWidth = bw + 'px';
                        }
                    }
                }
            }

            if (type === 'title') {
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var dtEl = doc.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (dtEl) {
                        var dtWrap = dtEl.querySelector('.impulse-display-text');
                        var dtLines = dtEl.querySelectorAll('.impulse-dt-line');
                        
                        for (var li = 0; li < dtLines.length; li++) {
                            var lineN = dtLines[li].dataset.line || (li + 1);
                            var lSize = resolvedSettings['line_' + lineN + '_size'];
                            var lWeight = resolvedSettings['line_' + lineN + '_weight'];
                            var lColor = resolvedSettings['line_' + lineN + '_color'];
                            var lGrad2 = resolvedSettings['line_' + lineN + '_grad_2'];
                            var lGradA = resolvedSettings['line_1_grad_angle']; 
                            var lFont = resolvedSettings['line_' + lineN + '_font'];
                            var lText = resolvedSettings['line_' + lineN];

                            

                            

                            
                            var fillInput = document.querySelector('input[name="line_' + lineN + '_fill"]');
                            var _savedFill = resolvedSettings['line_' + lineN + '_fill'] || (fillInput && fillInput.value) || '';
                            var lFill;
                            if (_savedFill === 'gradient' || _savedFill === 'solid') {
                                lFill = _savedFill;
                            } else {

                                lFill = (lGrad2 && lGrad2 !== '' && lGrad2 !== 'transparent') ? 'gradient' : 'solid';
                            }
                            if (fillInput && fillInput.value !== lFill) fillInput.value = lFill;
                            var grad1Input = document.querySelector('input[name="line_' + lineN + '_grad_1"]');
                            if (grad1Input && lFill === 'gradient' && lColor) grad1Input.value = lColor;
                            if (lSize) dtLines[li].style.fontSize = lSize + 'px';
                            if (lWeight) dtLines[li].style.fontWeight = lWeight;
                            if (lFill === 'gradient' && lColor && lGrad2) {
                                dtLines[li].style.background = 'linear-gradient(' + (lGradA != null && lGradA !== '' ? parseInt(lGradA) : 135) + 'deg,' + lColor + ',' + lGrad2 + ')';
                                dtLines[li].style.webkitBackgroundClip = 'text';
                                dtLines[li].style.webkitTextFillColor = 'transparent';
                                dtLines[li].style.backgroundClip = 'text';
                                dtLines[li].style.color = '';
                            } else if (lColor) {
                                dtLines[li].style.color = lColor;
                                dtLines[li].style.background = 'none';
                                dtLines[li].style.webkitBackgroundClip = 'initial';
                                dtLines[li].style.webkitTextFillColor = lColor;
                                dtLines[li].style.backgroundClip = 'initial';
                            }
                            if (lFont !== undefined) {
                                dtLines[li].style.fontFamily = lFont ? "'" + lFont + "',sans-serif" : '';
                            }
                            if (lText !== undefined) {
                                if (lText === '') {
                                    dtLines[li].textContent = '';
                                    dtLines[li].classList.add('is-empty');
                                } else {

                                    
                                    var _dtEsc = document.createElement('div');
                                    _dtEsc.textContent = lText;
                                    dtLines[li].innerHTML = _dtEsc.innerHTML
                                        .replace(/&amp;nbsp;/g, '&nbsp;')
                                        .replace(/&lt;(\/?(?:br|b|i|u|strong|em|sup|sub|small|mark))\s*\/?&gt;/gi,
                                            function(_m, tag) { return '<' + tag.toLowerCase() + '>'; });
                                    dtLines[li].classList.remove('is-empty');
                                }
                            }
                        }

                        

                        

                        

                        

                        

                        
                        
                        if (!window._impulseAlignCache) window._impulseAlignCache = {};
                        var dtAlignHidden = document.querySelector('#impulse-settings-body input[name="align"]');
                        var _hiddenAlignVal = (dtAlignHidden && dtAlignHidden.value) ? String(dtAlignHidden.value).trim() : '';
                        var _existingAlign = '';
                        try {
                            var _existSet = $('.impulse-panel-right').data('existing-settings') || {};
                            _existingAlign = _existSet.align ? String(_existSet.align).trim() : '';
                        } catch (_eA) {}
                        var _domAlign = '';
                        try {
                            var _ifrAlign = document.getElementById('impulse-iframe');
                            var _docAlign = _ifrAlign && (_ifrAlign.contentDocument || _ifrAlign.contentWindow.document);
                            var _wrapAlign = _docAlign && _docAlign.querySelector('.impulse-el[data-id="' + id + '"] .impulse-display-text');
                            if (_wrapAlign && _wrapAlign.style.textAlign) {
                                _domAlign = _wrapAlign.style.textAlign;
                            }
                        } catch (_eB) {}
                        var dtAlign = window._impulseAlignCache[id]
                            || _hiddenAlignVal
                            || (resolvedSettings.align ? String(resolvedSettings.align).trim() : '')
                            || _existingAlign
                            || _domAlign
                            || 'center';
                        if (dtAlignHidden) dtAlignHidden.value = dtAlign;
                        var _iframe = document.getElementById('impulse-iframe');
                        if (_iframe && _iframe.contentWindow) {
                            _iframe.contentWindow.postMessage({
                                type: 'impulse-dt-align',
                                elementId: id,
                                align: dtAlign,
                                maxWidth: parseInt(resolvedSettings.max_width) || 0,
                                letterSpacing: parseInt(resolvedSettings.letter_spacing) || 0
                            }, '*');
                        }

                        
                        if (dtWrap) {
                            
                            if (_has3d) {
                                dtWrap.setAttribute('data-dt-3d-mode', 'depth');
                            } else {
                                dtWrap.removeAttribute('data-dt-3d-mode');
                            }
                            dtWrap.setAttribute('data-dt-perspective', parseInt(resolvedSettings.perspective) || 800);
                            dtWrap.setAttribute('data-dt-layer-gap', parseInt(resolvedSettings.layer_gap) || 0);
                            dtWrap.setAttribute('data-dt-stroke-width', Math.max(1, Math.min(10, parseInt(resolvedSettings.stroke_width) || 1)));
                            dtWrap.setAttribute('data-dt-line-1-stroke', resolvedSettings.line_1_stroke || '');

                            dtWrap.setAttribute('data-dt-line-1-stroke-2', resolvedSettings.line_1_stroke_2 || '');
                            dtWrap.setAttribute('data-dt-stroke-rotate-speed', parseFloat(resolvedSettings.stroke_rotate_speed) || 0);
                            dtWrap.setAttribute('data-dt-stroke-bevel', resolvedSettings.stroke_bevel ? '1' : '0');
                            dtWrap.setAttribute('data-dt-stroke-spin-mode', (resolvedSettings.stroke_spin_mode === 'pulse') ? 'pulse' : 'sweep');
                            if (resolvedSettings.mouse_sensitive) dtWrap.setAttribute('data-dt-mouse', '1');
                            else dtWrap.removeAttribute('data-dt-mouse');
                            if (resolvedSettings.depth_of_field) dtWrap.setAttribute('data-dt-dof', parseInt(resolvedSettings.dof_intensity) || 50);
                            else dtWrap.removeAttribute('data-dt-dof');
                            if (resolvedSettings.depth_shadow) dtWrap.setAttribute('data-dt-shadow', '1');
                            else dtWrap.removeAttribute('data-dt-shadow');
                            dtWrap.setAttribute('data-dt-stroke-enabled', resolvedSettings.stroke_enabled ? '1' : '0');
                            dtWrap.querySelectorAll('.impulse-dt-line[data-line]').forEach(function(lEl) {
                                var ln = lEl.getAttribute('data-line');
                                var dz = parseInt(resolvedSettings['line_' + ln + '_depth']) || 0;
                                lEl.setAttribute('data-depth', dz);
                                lEl.setAttribute('data-base-z', dz);
                                
                                var _fill = resolvedSettings['line_' + ln + '_fill'] || 'solid';
                                lEl.setAttribute('data-fill', _fill);
                                if (_fill === 'gradient') {
                                    lEl.setAttribute('data-grad-1', resolvedSettings['line_' + ln + '_grad_1'] || '#000000');
                                    lEl.setAttribute('data-grad-2', resolvedSettings['line_' + ln + '_grad_2'] || '#ffffff');
                                    lEl.setAttribute('data-grad-angle', parseInt(resolvedSettings['line_' + ln + '_grad_angle']) || 135);
                                } else {
                                    lEl.setAttribute('data-color', resolvedSettings['line_' + ln + '_color'] || ''+ImpC.surface2+'');
                                    lEl.removeAttribute('data-grad-1'); lEl.removeAttribute('data-grad-2'); lEl.removeAttribute('data-grad-angle');
                                }
                            });
                        }

                        var _dt3dStructural = ['perspective','layer_gap',
                            'line_1_depth','line_1_yrot',
                            'depth_effects','depth_of_field','dof_intensity',
                            'depth_shadow','stroke_enabled','line_1_stroke','line_1_stroke_2',
                            'stroke_width','stroke_rotate_speed','stroke_bevel','stroke_spin_mode','layer_gap',
                            'line_1_weight','line_1_size','line_1_font',
                            'line_1',
                            'font_family','letter_spacing','align'];

                        

                        

                        

                        
                        
                        if (!window._dt3dPrevSnap) {
                            var _engineLive = false;
                            try {
                                var _dtIfrCheck = document.getElementById('impulse-iframe');
                                var _i3dWin = _dtIfrCheck && _dtIfrCheck.contentWindow;
                                var _i3dApi = _i3dWin && _i3dWin.Impulse3DText;
                                _engineLive = !!(_i3dApi && _i3dApi.instances && _i3dApi.instances[id]);
                            } catch (_e) {}
                            if (_engineLive) {
                                window._dt3dPrevSnap = {};
                                _dt3dStructural.forEach(function(k) { window._dt3dPrevSnap[k] = resolvedSettings[k]||''; });
                                window._dt3dPrevSnap['line_1_color']     = resolvedSettings['line_1_color']     || '';
                                window._dt3dPrevSnap['line_1_grad_1']    = resolvedSettings['line_1_grad_1']    || '';
                                window._dt3dPrevSnap['line_1_grad_2']    = resolvedSettings['line_1_grad_2']    || '';
                                window._dt3dPrevSnap['line_1_fill']      = resolvedSettings['line_1_fill']      || '';
                                window._dt3dPrevSnap['line_1_grad_angle']= resolvedSettings['line_1_grad_angle']|| '';
                            }
                        }
                        var _dtPrevSnap = window._dt3dPrevSnap || {};
                        var _dt3dNeedsReinit = !window._dt3dPrevSnap; 
                        _dt3dStructural.forEach(function(k) {
                            if ((resolvedSettings[k]||'') !== (_dtPrevSnap[k]||'')) _dt3dNeedsReinit = true;
                        });

                        var _depthOn   = !!(resolvedSettings.depth_effects);
                        var _depthPrev = !!(_dtPrevSnap.depth_effects);
                        
                        var _strokeNow  = !!(resolvedSettings.stroke_enabled);
                        var _strokePrev2 = !!(_dtPrevSnap.stroke_enabled);
                        var _has3d = _depthOn || (parseInt(resolvedSettings.line_1_depth)||0) !== 0 || (parseInt(resolvedSettings.line_1_yrot)||0) !== 0 || _strokeNow;
                        var _had3d = _depthPrev || (parseInt(_dtPrevSnap.line_1_depth)||0) !== 0 || (parseInt(_dtPrevSnap.line_1_yrot)||0) !== 0 || _strokePrev2;
                        var _snapSettings = {
                            perspective:  parseInt(resolvedSettings.perspective) || 800,
                            dof:          _depthOn ? (parseInt(resolvedSettings.dof_intensity) || 0) : 0,
                            shadow:       _depthOn && !!(resolvedSettings.depth_shadow),
                            
                            mouse:        !!(parseInt(resolvedSettings.line_1_depth)||0) !== 0 || !!(parseInt(resolvedSettings.line_1_yrot)||0) !== 0 || _depthOn || _strokeNow,
                            strokeWidth:  Math.max(1, Math.min(10, parseInt(resolvedSettings.stroke_width) || 1)),
                            layerGap:     parseInt(resolvedSettings.layer_gap) || 0,
                            line1stroke:  resolvedSettings.line_1_stroke || '',
                            line1stroke2: resolvedSettings.line_1_stroke_2 || '',
                            strokeRotateSpeed: parseFloat(resolvedSettings.stroke_rotate_speed) || 0,
                            strokeBevel:  !!resolvedSettings.stroke_bevel,
                            strokeSpinMode: (resolvedSettings.stroke_spin_mode === 'pulse') ? 'pulse' : 'sweep',
                            lineDepths: { 1: parseInt(resolvedSettings.line_1_depth) || 0 },
                            lineYRots:  { 1: parseInt(resolvedSettings.line_1_yrot) || 0 },
                            mouseSens:    (resolvedSettings.mouse_sens != null && resolvedSettings.mouse_sens !== '' ? parseFloat(resolvedSettings.mouse_sens) : 5),
                            orbitSpeed:   (resolvedSettings.orbit_speed != null && resolvedSettings.orbit_speed !== '' ? parseFloat(resolvedSettings.orbit_speed) : 5),
                            strokeEnabled: !!(resolvedSettings.stroke_enabled),
                            letterSpacing: parseInt(resolvedSettings.letter_spacing) || 0,
                            autoTilt:     !!(resolvedSettings.auto_tilt && resolvedSettings.auto_tilt != '0' && resolvedSettings.auto_tilt !== false),
                            depthEffectsOn: _depthOn
                        };
                        window._dt3dPrevSnap = {};
                        _dt3dStructural.forEach(function(k) { window._dt3dPrevSnap[k] = resolvedSettings[k]||''; });
                        
                        var _colorKeys = ['line_1_color','line_1_grad_1','line_1_grad_2','line_1_fill'];
                        _colorKeys.forEach(function(k) { window._dt3dPrevSnap[k] = resolvedSettings[k]||''; });
                        window._dt3dPrevSnap['line_1_grad_angle'] = resolvedSettings['line_1_grad_angle']||'';
                        window._dt3dPrevSnap['line_1_fill'] = resolvedSettings['line_1_fill']||'';
                        window._dt3dPrevSnap['stroke_enabled'] = resolvedSettings['stroke_enabled']||'';
                        window._dt3dPrevSnap['line_1_stroke'] = resolvedSettings['line_1_stroke']||'';

                        

                        

                        
                        var _rebuildKeys = [
                            'line_1_weight','line_1_size','line_1_font',
                            'font_family','letter_spacing','align',
                            'stroke_enabled','line_1_stroke'
                        ];
                        var _needsRebuild = _dt3dNeedsReinit && _rebuildKeys.some(function(k) {
                            return (resolvedSettings[k]||'') !== (_dtPrevSnap[k]||'');
                        });
                        var _colorsOnly = !_dt3dNeedsReinit && _colorKeys.some(function(k) {
                            return (resolvedSettings[k]||'') !== (_dtPrevSnap[k]||'');
                        });

                        

                        

                        

                        

                        var _opticsChanged = _dt3dNeedsReinit && !_needsRebuild && [
                            'perspective','dof_intensity','depth_shadow','layer_gap','depth_of_field','depth_effects',
                            'line_1_depth','line_1_yrot',
                            'stroke_width','stroke_rotate_speed','stroke_bevel','stroke_spin_mode','line_1_stroke','line_1_stroke_2'
                        ].some(function(k) { return (resolvedSettings[k]||'') !== (_dtPrevSnap[k]||''); });

                        var _gradAngleOnly = !_dt3dNeedsReinit && (resolvedSettings['line_1_grad_angle']||'') !== (_dtPrevSnap['line_1_grad_angle']||'');

                        
                        clearTimeout(window._dt3dReinitTimer);
                        var _dt3dId = id;
                        var _snap3d = JSON.parse(JSON.stringify(_snapSettings));
                        var _snapGradAngle = resolvedSettings['line_1_grad_angle'];

                        
                        
                        var _snapColor   = resolvedSettings['line_1_color'];
                        var _snapGrad1   = resolvedSettings['line_1_grad_1'];
                        var _snapGrad2   = resolvedSettings['line_1_grad_2'];
                        var _snapFill    = resolvedSettings['line_1_fill'];
                        window._dt3dReinitTimer = setTimeout(function() {
                            var _dtIframe = document.getElementById('impulse-iframe');
                            if (!_dtIframe || !_dtIframe.contentWindow) return;
                            
                            if (_gradAngleOnly) {
                                _dtIframe.contentWindow.postMessage({ type: 'impulse-3d-text-update', id: _dt3dId, prop: 'gradAngle', value: _snapGradAngle != null ? parseFloat(_snapGradAngle) : 135 }, '*');
                                return;
                            }

                            

                            

                            
                            if (_colorsOnly) {
                                _dtIframe.contentWindow.postMessage({
                                    type: 'impulse-3d-text-update',
                                    id:   _dt3dId,
                                    prop: 'colors',
                                    value: {
                                        1: {
                                            color: _snapColor || '#1d2327',
                                            grad1: (_snapFill === 'gradient') ? (_snapGrad1 || _snapColor || '') : '',
                                            grad2: (_snapFill === 'gradient') ? (_snapGrad2 || '') : ''
                                        }
                                    }
                                }, '*');
                                return;
                            }

                            

                            

                            

                            if (_opticsChanged && _has3d) {
                                _dtIframe.contentWindow.postMessage({
                                    type: 'impulse-3d-text-update',
                                    id:   _dt3dId,
                                    prop: 'optics',
                                    value: {
                                        perspective: _snap3d.perspective,
                                        dof:         _snap3d.dof,
                                        shadow:      _snap3d.shadow,
                                        layerGap:    _snap3d.layerGap,
                                        lineDepth:   _snap3d.lineDepths && _snap3d.lineDepths[1],
                                        lineYRot:    _snap3d.lineYRots  && _snap3d.lineYRots[1]
                                    }
                                }, '*');

                                

                                
                                if ((resolvedSettings['stroke_width']||'') !== (_dtPrevSnap['stroke_width']||'')) {
                                    _dtIframe.contentWindow.postMessage({
                                        type: 'impulse-3d-text-update',
                                        id:   _dt3dId,
                                        prop: 'strokeWidth',
                                        value: _snap3d.strokeWidth
                                    }, '*');
                                }
                                if ((resolvedSettings['line_1_stroke']||'')     !== (_dtPrevSnap['line_1_stroke']||'')     ||
                                    (resolvedSettings['line_1_stroke_2']||'')   !== (_dtPrevSnap['line_1_stroke_2']||'')   ||
                                    (resolvedSettings['stroke_bevel']||'')      !== (_dtPrevSnap['stroke_bevel']||'')      ||
                                    (resolvedSettings['stroke_spin_mode']||'')  !== (_dtPrevSnap['stroke_spin_mode']||'')  ||
                                    (resolvedSettings['stroke_rotate_speed']||'') !== (_dtPrevSnap['stroke_rotate_speed']||'')) {
                                    _dtIframe.contentWindow.postMessage({
                                        type: 'impulse-3d-text-update',
                                        id:   _dt3dId,
                                        prop: 'strokeColors',
                                        value: {
                                            c1:          _snap3d.line1stroke,
                                            c2:          _snap3d.line1stroke2,
                                            bevel:       _snap3d.strokeBevel,
                                            rotateSpeed: _snap3d.strokeRotateSpeed,
                                            spinMode:    _snap3d.strokeSpinMode
                                        }
                                    }, '*');
                                }
                                return;
                            }
                            if (!_has3d) {
                                
                                _dtIframe.contentWindow.postMessage({ type: 'impulse-3d-text-destroy', id: _dt3dId }, '*');
                                return;
                            }

                            

                            

                            var _dtEngineLive = false;
                            try {
                                var _dtEW = _dtIframe.contentWindow;
                                _dtEngineLive = !!(_dtEW.Impulse3DText && _dtEW.Impulse3DText.instances && _dtEW.Impulse3DText.instances[_dt3dId]);
                            } catch (_eLive) {}
                            var _dt3dMsg = _dtEngineLive ? 'impulse-3d-text-reinit' : 'impulse-3d-text-init';
                            _dtIframe.contentWindow.postMessage({ type: _dt3dMsg, id: _dt3dId, settings: _snap3d }, '*');
                            
                            if (['line_1_font','font_family'].some(function(k) {
                                return (resolvedSettings[k]||'') !== (_dtPrevSnap[k]||'');
                            })) {
                                setTimeout(function() {
                                    var _fi2 = document.getElementById('impulse-iframe');
                                    if (_fi2 && _fi2.contentWindow) {
                                        var _live2 = false;
                                        try {
                                            var _eW2 = _fi2.contentWindow;
                                            _live2 = !!(_eW2.Impulse3DText && _eW2.Impulse3DText.instances && _eW2.Impulse3DText.instances[_dt3dId]);
                                        } catch (_e2) {}
                                        _fi2.contentWindow.postMessage({ type: _live2 ? 'impulse-3d-text-reinit' : 'impulse-3d-text-init', id: _dt3dId, settings: _snap3d }, '*');
                                    }
                                }, 500);
                            }
                        }, 80);
                    }
                }
            }

            

            

            

            

            

            
            if (type === 'button') {
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var btnEl  = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-button');
                    var btnWrap= doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-button-wrap');
                    if (btnWrap) {
                        var _alignMap = { left: 'flex-start', center: 'center', right: 'flex-end', full: 'stretch' };
                        var _alignNow = window._impulseAlignCache && window._impulseAlignCache[id];
                        if (!_alignNow) _alignNow = resolvedSettings.align || 'center';
                        btnWrap.style.setProperty('--impulse-btn-justify', _alignMap[_alignNow] || 'center');
                        if (btnEl) btnEl.style.width = (_alignNow === 'full') ? '100%' : '';
                    }
                }
            }

            

            

            
            
            if (type === 'divider') {
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var divEl = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-divider');
                    if (divEl && resolvedSettings.width !== undefined) {
                        divEl.style.width = parseInt(resolvedSettings.width) + '%';
                    }
                }
                return 'needs-refresh';
            }

            

            
            
            if (type === 'code') {
                return 'needs-refresh';
            }

            

            if (type === 'configurator') {
                return 'needs-refresh';
            }
            
            if (type === 'map') {
                var prevSettings = window.googleMapPrevSettings || {};
                if (prevSettings.address !== settings.address || 
                    prevSettings.zoom !== resolvedSettings.zoom || 
                    prevSettings.map_type !== settings.map_type ||
                    prevSettings.map_shape !== settings.map_shape ||
                    prevSettings.map_style !== settings.map_style ||
                    prevSettings.pin_pulse !== settings.pin_pulse ||
                    prevSettings.width !== resolvedSettings.width) {
                    window.googleMapPrevSettings = $.extend({}, settings, { zoom: resolvedSettings.zoom, width: resolvedSettings.width });
                    return 'needs-refresh';
                }
                window.googleMapPrevSettings = $.extend({}, settings, { zoom: resolvedSettings.zoom, width: resolvedSettings.width });
            }

            if (type === 'text') {
                window.textPrev = JSON.parse(JSON.stringify(settings));
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var _tWrap = doc.querySelector('.impulse-el[data-id="' + id + '"]');
                    var _tEl = _tWrap ? _tWrap.querySelector('.impulse-text') : null;
                    if (_tEl) {
                        _tEl.style.columnCount  = parseInt(resolvedSettings.columns) > 1 ? parseInt(resolvedSettings.columns) : '';
                        _tEl.style.fontStyle    = resolvedSettings.italic ? 'italic' : '';
                        var _dec = resolvedSettings.decoration || '';
                        _tEl.style.textDecoration = (_dec && _dec !== 'none') ? _dec : '';
                        _tEl.classList.toggle('impulse-drop-cap', !!resolvedSettings.drop_cap);
                    }

                    

                    

                    
                    if (_tWrap) {
                        var _tw = parseInt(resolvedSettings.width) || 100;

                        var _tAlign = resolvedSettings.box_align || resolvedSettings.align || 'center';
                        if (_tw > 0 && _tw < 100) {
                            _tWrap.style.width = _tw + '%';
                            _tWrap.style.maxWidth = 'min(' + _tw + '%, 1200px)';
                            if (_tAlign === 'left')      { _tWrap.style.marginLeft = '0';    _tWrap.style.marginRight = 'auto'; }
                            else if (_tAlign === 'right') { _tWrap.style.marginLeft = 'auto'; _tWrap.style.marginRight = '0';    }
                            else                          { _tWrap.style.marginLeft = 'auto'; _tWrap.style.marginRight = 'auto'; }
                        } else {

                            

                            
                            
                            _tWrap.style.width = '';
                            _tWrap.style.maxWidth = '1200px';
                            if (_tAlign === 'left')      { _tWrap.style.marginLeft = '0';    _tWrap.style.marginRight = 'auto'; }
                            else if (_tAlign === 'right') { _tWrap.style.marginLeft = 'auto'; _tWrap.style.marginRight = '0';    }
                            else                          { _tWrap.style.marginLeft = 'auto'; _tWrap.style.marginRight = 'auto'; }
                        }
                    }
                }
            }

            if (type === 'section') {
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sectionEl = doc.querySelector('.impulse-el[data-id="' + id + '"] section.impulse-section');
                    if (sectionEl) {
                        if (resolvedSettings.bg_size) sectionEl.style.backgroundSize = resolvedSettings.bg_size;
                        if (resolvedSettings.bg_position) sectionEl.style.backgroundPosition = resolvedSettings.bg_position;
                        if (resolvedSettings.border_radius !== undefined) sectionEl.style.borderRadius = parseInt(resolvedSettings.border_radius) + 'px';
                        
                        if (resolvedSettings.border_width !== undefined) sectionEl.style.borderWidth = parseInt(resolvedSettings.border_width) + 'px';
                        if (resolvedSettings.border_color) sectionEl.style.borderColor = resolvedSettings.border_color;
                        if (resolvedSettings.border_width !== undefined || resolvedSettings.border_color) sectionEl.style.borderStyle = (parseInt(resolvedSettings.border_width) > 0) ? 'solid' : 'none';
                        
                        if (resolvedSettings.bg_fixed !== undefined) sectionEl.style.backgroundAttachment = resolvedSettings.bg_fixed ? 'fixed' : '';
                        var shadowMap = {
                            none: 'none',
                            sm: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08)',
                            md: '0 4px 6px rgba(0,0,0,0.1), 0 2px 4px rgba(0,0,0,0.06)',
                            lg: '0 10px 15px rgba(0,0,0,0.1), 0 4px 6px rgba(0,0,0,0.05)',
                            xl: '0 20px 25px rgba(0,0,0,0.1), 0 8px 10px rgba(0,0,0,0.04)'
                        };
                        if (resolvedSettings.shadow !== undefined) sectionEl.style.boxShadow = shadowMap[resolvedSettings.shadow] || 'none';

                        if (resolvedSettings.bg_parallax_sens !== undefined) {
                            try {
                                var _ifrEl  = document.getElementById('impulse-iframe');
                                var _ifrWin = _ifrEl && _ifrEl.contentWindow;
                                if (_ifrWin && _ifrWin.ImpulseBgParallax && _ifrWin.ImpulseBgParallax.setSens) {
                                    _ifrWin.ImpulseBgParallax.setSens(sectionEl, resolvedSettings.bg_parallax_sens);
                                }
                            } catch (_e) {}
                        }

                        

                        

                        if (resolvedSettings.bg_depth_strength !== undefined) {
                            try {
                                var _dsRaw = parseInt(resolvedSettings.bg_depth_strength) || 0;
                                var _dsIfr = document.getElementById('impulse-iframe');
                                var _dsWin = _dsIfr && _dsIfr.contentWindow;
                                if (_dsWin) {
                                    _dsWin.postMessage({ type: 'impulse-depth-strength', strength: _dsRaw / 100 }, '*');
                                }
                                if (_dsRaw > 0 && !resolvedSettings.bg_depth_map && resolvedSettings.bg_image
                                    && typeof _autoGenSectionDepth === 'function') {
                                    _autoGenSectionDepth(resolvedSettings.bg_image, null);
                                }
                            } catch (_e) {}
                        }

                        var _bgClr = resolvedSettings.bg_color;
                        var _meshClean = function (c) {
                            c = (c || '') + '';
                            if (!c || c === 'transparent') return '';
                            if (c.indexOf('rgba(0,0,0,0)') === 0) return '';
                            return c;
                        };
                        var _meshList = [
                            _meshClean(_bgClr),
                            _meshClean(resolvedSettings.bg_color_2),
                            _meshClean(resolvedSettings.bg_color_3),
                            _meshClean(resolvedSettings.bg_color_4)
                        ].filter(function (c) { return c !== ''; });
                        var _meshCount = _meshList.length;
                        var _hasMesh = _meshCount >= 2;
                        var _mesh = sectionEl.querySelector(':scope > .impulse-mesh');

                        

                        
                        
                        var _meshTouched = (resolvedSettings.bg_color_2 !== undefined
                                         || resolvedSettings.bg_color_3 !== undefined
                                         || resolvedSettings.bg_color_4 !== undefined);
                        if (_hasMesh) {
                            
                            if (!_mesh) {
                                _mesh = document.createElement('div');
                                _mesh.className = 'impulse-mesh';
                                _mesh.setAttribute('aria-hidden', 'true');
                                var _fxInit = document.createElement('div');
                                _fxInit.className = 'impulse-mesh-fx';
                                _fxInit.style.cssText =
                                    'background:'
                                    + 'radial-gradient(at var(--imp-mesh-x1) var(--imp-mesh-y1),var(--imp-mesh-c1) 0%,transparent 50%),'
                                    + 'radial-gradient(at var(--imp-mesh-x2) var(--imp-mesh-y2),var(--imp-mesh-c2) 0%,transparent 50%),'
                                    + 'radial-gradient(at var(--imp-mesh-x3) var(--imp-mesh-y3),var(--imp-mesh-c3) 0%,transparent 50%),'
                                    + 'radial-gradient(at var(--imp-mesh-x4) var(--imp-mesh-y4),var(--imp-mesh-c4) 0%,transparent 50%),'
                                    + 'var(--imp-mesh-base);'
                                    + 'background-size:140% 140%;'
                                    + 'animation:imp-mesh-drift 10s ease-in-out infinite alternate;';
                                _mesh.appendChild(_fxInit);
                                sectionEl.insertBefore(_mesh, sectionEl.firstChild);
                            }
                            
                            var _slotKeysLP = ['bg_color', 'bg_color_2', 'bg_color_3', 'bg_color_4'];
                            var _slotDefLP  = [[10,10], [90,10], [10,90], [90,90]];
                            var _meshSlots  = [];
                            for (var _si = 0; _si < _slotKeysLP.length; _si++) {
                                var _sk     = _slotKeysLP[_si];
                                var _slotC  = _meshClean(resolvedSettings[_sk]);
                                if (_si === 0 && _slotC === '') _slotC = _meshClean(_bgClr);
                                if (_slotC === '') continue;
                                var _sbx = parseInt(resolvedSettings[_sk + '_x']);
                                var _sby = parseInt(resolvedSettings[_sk + '_y']);
                                if (isNaN(_sbx)) _sbx = _slotDefLP[_si][0];
                                if (isNaN(_sby)) _sby = _slotDefLP[_si][1];
                                _meshSlots.push({ color: _slotC, bx: _sbx, by: _sby });
                            }
                            
                            while (_meshSlots.length < 4) {
                                _meshSlots.push({ color: 'rgba(0,0,0,0)', bx: 50, by: 50 });
                            }
                            _meshCount = _meshSlots.filter(function (s) { return s.color !== 'rgba(0,0,0,0)'; }).length;
                            
                            for (var _vi = 0; _vi < 4; _vi++) {
                                var _slot = _meshSlots[_vi];
                                var _n = _vi + 1;
                                _mesh.style.setProperty('--imp-mesh-c' + _n, _slot.color);
                                _mesh.style.setProperty('--imp-mesh-x' + _n, _slot.bx + '%');
                                _mesh.style.setProperty('--imp-mesh-y' + _n, _slot.by + '%');
                            }
                            
                            var _explicitBase = _meshClean(resolvedSettings.mesh_base_color);
                            var _baseClr;
                            if (_explicitBase) {
                                _baseClr = _explicitBase;
                            } else {
                                var _b1 = (typeof _bgClr === 'string') ? _bgClr.trim() : '';
                                var _b1Opaque = false;
                                if (_b1 && _b1 !== 'transparent') {
                                    var _hx = /^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(_b1);
                                    if (_hx) { _b1Opaque = !_hx[2] || parseInt(_hx[2], 16) >= 242; }
                                    else if (/^#[0-9a-fA-F]{3}$/.test(_b1)) { _b1Opaque = true; }
                                    else {
                                        var _rm = /rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([\d.]+))?\s*\)/i.exec(_b1);
                                        _b1Opaque = _rm ? (_rm[1] === undefined || _rm[1] === '' || parseFloat(_rm[1]) >= 0.95) : true;
                                    }
                                }
                                _baseClr = _b1Opaque ? _b1 : '#0a0c12';
                            }
                            _mesh.style.setProperty('--imp-mesh-base', _baseClr);
                            
                            var _staleHCont = sectionEl.querySelector(':scope > .impulse-mesh-handles');
                            if (_staleHCont) _staleHCont.remove();
                            var _staleSvg = _mesh.querySelector(':scope > svg[data-distort-id]');
                            if (_staleSvg) _staleSvg.remove();
                            _mesh.setAttribute('data-count', _meshCount);
                            
                            var _spd10 = Math.max(0, Math.min(10, parseInt(resolvedSettings.bg_mesh_speed)));
                            if (!isNaN(_spd10)) {

                                
                                var _period = _spd10 > 0 ? (4 + (10 - _spd10) * 2) : 0;
                                _mesh.style.setProperty('--imp-mesh-spd', Math.max(1, _period) + 's');
                                var _fxNow = _mesh.querySelector(':scope > .impulse-mesh-fx');
                                if (_fxNow) {
                                    _fxNow.style.animationDuration = Math.max(1, _period) + 's';
                                    _fxNow.style.animationPlayState = _spd10 === 0 ? 'paused' : 'running';
                                }
                            }
                            
                            var _op = parseInt(resolvedSettings.bg_mesh_alpha);
                            if (isNaN(_op)) _op = 100;
                            _op = Math.max(0, Math.min(100, _op));
                            _mesh.style.setProperty('--imp-mesh-op', (_op / 100));
                            _mesh.classList.toggle('impulse-mesh-static',  (_spd10 === 0));
                            
                            sectionEl.style.setProperty('background-color', 'transparent');
                            sectionEl.style.removeProperty('--impulse-bg-color');
                        } else if (!_mesh || _meshTouched) {
                            if (_mesh) _mesh.parentNode.removeChild(_mesh);

                            
                            var _hContainerDrop = sectionEl.querySelector(':scope > .impulse-mesh-handles');
                            if (_hContainerDrop) _hContainerDrop.remove();

                            sectionEl.classList.remove('has-mesh-ragged');

                            

                            

                            

                            

                            

                            

                            
                            var _isTranspClr = function (c) {
                                return (typeof c !== 'string' || c === '' || c === 'transparent' || c.indexOf('rgba(0,0,0,0)') === 0);
                            };

                            
                            
                            var _effBase = !_isTranspClr(resolvedSettings.mesh_base_color) ? resolvedSettings.mesh_base_color : _bgClr;
                            if (!_isTranspClr(_effBase)) {
                                sectionEl.style.setProperty('--impulse-bg-color', _effBase);
                                sectionEl.style.setProperty('background-color', 'var(--impulse-bg-color, transparent)');
                            } else {
                                sectionEl.style.removeProperty('--impulse-bg-color');
                                sectionEl.style.setProperty('background-color', 'transparent');
                            }
                        }
                    }

                    
                    var _ovEl = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-section-overlay');
                    var _ovOp = resolvedSettings.overlay_opacity !== undefined ? parseFloat(resolvedSettings.overlay_opacity) / 100 : 0;
                    if (_ovOp > 0) {
                        if (!_ovEl) {
                            var _secHost = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-section');
                            if (_secHost) {
                                _ovEl = doc.createElement('div');
                                _ovEl.className = 'impulse-section-overlay';
                                _ovEl.style.cssText = 'position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none;z-index:1';
                                _secHost.appendChild(_ovEl);
                            }
                        }
                        if (_ovEl) {
                            _ovEl.style.backgroundColor = resolvedSettings.overlay_color || 'transparent';
                            _ovEl.style.opacity = _ovOp;
                        }
                    } else if (_ovEl) {
                        _ovEl.parentNode.removeChild(_ovEl);
                    }
                    
                    var _cEl = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-container');
                    var _sEl2 = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-section');
                    if (_cEl) {

                        var _fw = resolvedSettings.full_width;
                        var _fwOn = (_fw === true || _fw === '1' || _fw === 'true' || _fw === 1);
                        if (_fwOn) {
                            _cEl.style.maxWidth = 'none';
                        } else {
                            var _pageMaxCW = (Impulse.pageSettings && parseInt(Impulse.pageSettings.max_content_width)) || 1440;
                            _cEl.style.maxWidth = _pageMaxCW > 0 ? _pageMaxCW + 'px' : 'none';
                        }
                        var _ca = resolvedSettings.content_align;
                        if (_ca) {
                            var _mMap = { left:['0','auto'], center:['auto','auto'], right:['auto','0'] };
                            var _m = _mMap[_ca] || _mMap.center;
                            _cEl.style.marginLeft = _m[0]; _cEl.style.marginRight = _m[1];
                        }
                        var _va = resolvedSettings.valign;
                        if (_va) {

                            
                            var _vaMap = {top:'flex-start',center:'center',bottom:'flex-end',between:'space-between',around:'space-around',evenly:'space-evenly'};
                            var _vaIsScreenRoot = false;
                            try {
                                var _parEl = _cEl.closest('.impulse-el[data-type="section"]');
                                var _wrapScr = _parEl && _parEl.parentElement && _parEl.parentElement.classList.contains('impulse-content-wrapper');
                                _vaIsScreenRoot = !!(Impulse.pageSettings && (true) && _wrapScr);
                            } catch(_e) {}
                            var _vaVal = _vaMap[_va] || 'center';
                            if (_vaIsScreenRoot && (_va === 'center' || _va === 'bottom')) {
                                _vaVal = 'safe ' + _vaVal;
                            }
                            _cEl.style.justifyContent = _vaVal;
                        }
                    }
                    if (_sEl2 && resolvedSettings.content_align) {
                        var _caMap2 = {left:'flex-start',center:'center',right:'flex-end'};
                        _sEl2.style.setProperty('--impulse-ca', _caMap2[resolvedSettings.content_align] || 'center');
                    }
                }

                var prev = window.sectionPrev || {};
                var _sStructKeys = ['direction','bg_animation_enabled','bg_image','bg_video','bg_video_fallback',

                    

                    'tw_text','tw_on','tw_motion','tw_weight','tw_size','tw_space','tw_gap','tw_speed','tw_spotlight','tw_parallax','tw_spot_size','tw_color'];
                function _sNorm(v) {
                    if (v === undefined || v === null || v === '' || v === 'transparent') return '';
                    if (v === true || v === 'true' || v === '1') return '1';
                    if (v === false || v === 'false' || v === '0') return '0';
                    return String(v);
                }
                var _sChanged = false;
                for (var _sk = 0; _sk < _sStructKeys.length; _sk++) {
                    var _k = _sStructKeys[_sk];
                    if (_sNorm(prev[_k]) !== _sNorm(settings[_k])) {
                        _sChanged = true;
                        break;
                    }
                }
                if (_sChanged) {
                    window.sectionPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.sectionPrev = JSON.parse(JSON.stringify(settings));
            }

            if (type === 'flip_box') {
                var prev = window.flipBoxPrev || null;

                var needsStructural = prev && (prev.animation_type !== settings.animation_type ||
                    prev.flip_direction !== settings.flip_direction ||
                    prev.slide_direction !== settings.slide_direction ||
                    (!!prev.back_button_text) !== (!!settings.back_button_text));
                if (needsStructural) {
                    window.flipBoxPrev = JSON.parse(JSON.stringify(settings));
                    if (!window._impulsePrevSettings) window._impulsePrevSettings = {};
                    window._impulsePrevSettings[id] = JSON.stringify(stripEntrance(settings));
                    return 'needs-refresh';
                }
                window.flipBoxPrev = JSON.parse(JSON.stringify(settings));

                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var s = resolvedSettings;

                    var h = parseInt(s.height) || 250;
                    css += sel + ' .impulse-flip-box { height: ' + h + 'px !important; }';

                    var mw = parseInt(s.section_max_width) || 0;
                    if (mw > 0) {
                        css += sel + ' .impulse-flip-box { max-width: ' + mw + 'px !important; margin-left: auto !important; margin-right: auto !important; }';
                    }

                    var br = parseInt(s.border_radius) || 0;
                    css += sel + ' .impulse-flip-front, ' + sel + ' .impulse-flip-back { border-radius: ' + br + 'px !important; }';

                    var pt = parseInt(s.padding_top) || 0;
                    var pr = parseInt(s.padding_right) || 0;
                    var pb = parseInt(s.padding_bottom) || 0;
                    var pl = parseInt(s.padding_left) || 0;
                    var uniformPad = s.padding !== undefined ? parseInt(s.padding) : null;
                    if (uniformPad !== null) {
                        css += sel + ' .impulse-flip-front, ' + sel + ' .impulse-flip-back { padding: ' + uniformPad + 'px !important; }';
                    } else {
                        css += sel + ' .impulse-flip-front, ' + sel + ' .impulse-flip-back { padding: ' + pt + 'px ' + pr + 'px ' + pb + 'px ' + pl + 'px !important; }';
                    }

                    if (s.front_bg) css += sel + ' .impulse-flip-front { background: ' + s.front_bg + ' !important; }';
                    if (s.front_color) css += sel + ' .impulse-flip-front { color: ' + s.front_color + ' !important; }';

                    if (s.back_bg) css += sel + ' .impulse-flip-back { background: ' + s.back_bg + ' !important; }';
                    if (s.back_color) css += sel + ' .impulse-flip-back { color: ' + s.back_color + ' !important; }';

                    var fts = parseInt(s.front_title_size) || 24;
                    var fcs = parseInt(s.front_content_size) || 14;
                    css += sel + ' .impulse-flip-title { font-size: ' + fts + 'px !important; }';
                    css += sel + ' .impulse-flip-content { font-size: ' + fcs + 'px !important; }';

                    var anim = s.animation_type || 'flip';
                    if (anim === 'cube') {
                        var tz = Math.round(h / 2);
                        css += sel + ' .impulse-flip-front { transform: translateZ(' + tz + 'px) !important; }';
                        css += sel + ' .impulse-flip-back { transform: rotateX(-90deg) translateZ(' + tz + 'px) !important; }';
                    }
                    
                    if (css) {
                        var styleId = 'impulse-live-flipbox-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }

                    var frontTitleEl = doc.querySelector(sel + ' .impulse-flip-front .impulse-flip-title');
                    if (frontTitleEl && s.front_title !== undefined) frontTitleEl.innerHTML = s.front_title || '';
                    var frontContentEl = doc.querySelector(sel + ' .impulse-flip-front .impulse-flip-content');
                    if (frontContentEl && s.front_content !== undefined) frontContentEl.innerHTML = s.front_content || '';
                    var backTitleEl = doc.querySelector(sel + ' .impulse-flip-back .impulse-flip-title');
                    if (backTitleEl && s.back_title !== undefined) backTitleEl.innerHTML = s.back_title || '';
                    var backContentEl = doc.querySelector(sel + ' .impulse-flip-back .impulse-flip-content');
                    if (backContentEl && s.back_content !== undefined) backContentEl.innerHTML = s.back_content || '';
                    
                    var backBtnEl = doc.querySelector(sel + ' .impulse-flip-back .impulse-flip-button');
                    if (backBtnEl) {
                        if (s.back_button_text !== undefined) backBtnEl.textContent = s.back_button_text || '';
                        if (s.back_button_link !== undefined) backBtnEl.setAttribute('href', s.back_button_link || '#');
                    }
                }
                
                if (!window._impulsePrevSettings) window._impulsePrevSettings = {};
                window._impulsePrevSettings[id] = JSON.stringify(stripEntrance(settings));
            }

            if (type === 'video') {
                var prev = window.videoPrev || {};
                if (prev.video_url !== settings.video_url ||
                    prev.aspect_ratio !== resolvedSettings.aspect_ratio ||
                    prev.width !== resolvedSettings.width ||
                    prev.mask_id !== settings.mask_id ||
                    prev.mask_url !== settings.mask_url ||
                    prev.mask_viewbox !== settings.mask_viewbox ||
                    prev.autoplay !== settings.autoplay ||
                    prev.controls !== settings.controls ||
                    prev.poster_url !== settings.poster_url) {
                    window.videoPrev = JSON.parse(JSON.stringify(resolvedSettings));
                    return 'needs-refresh';
                }
                window.videoPrev = JSON.parse(JSON.stringify(resolvedSettings));
            }

            if (type === 'icon_card') {
                
                if (!window.iconPrev) {
                    var _existIconBase = $('.impulse-panel-right').data('existing-settings') || {};
                    window.iconPrev = JSON.parse(JSON.stringify(_existIconBase));
                }
                var prev = window.iconPrev;
                if (prev.icon !== settings.icon ||
                    prev.icon_image !== settings.icon_image ||
                    prev.view !== settings.view ||
                    prev.hover_effect !== settings.hover_effect ||
                    prev.continuous_effect !== settings.continuous_effect ||
                    prev.text_position !== settings.text_position ||
                    prev.link !== settings.link ||
                    prev.new_tab !== settings.new_tab ||
                    prev.ib_mouse !== settings.ib_mouse ||
                    prev.ib_dof !== settings.ib_dof ||
                    prev.ib_chromatic !== settings.ib_chromatic ||
                    prev.ib_orbit !== settings.ib_orbit) {
                    window.iconPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.iconPrev = JSON.parse(JSON.stringify(settings));
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var s = resolvedSettings;
                    
                    var iconWrap = doc.querySelector(sel + ' .impulse-icon-wrap');
                    if (iconWrap) {
                        var sizeVal = parseInt(s.size) || 48;
                        var viewMode = s.view || 'default';
                        iconWrap.setAttribute('data-view', viewMode);
                        if (viewMode === 'stacked' || viewMode === 'framed' || viewMode === 'square') {
                            if (s.icon_image) {
                                iconWrap.style.width = sizeVal + 'px';
                                iconWrap.style.height = sizeVal + 'px';
                            } else {
                                iconWrap.style.fontSize = sizeVal + 'px';
                            }
                        } else {
                            iconWrap.style.fontSize = sizeVal + 'px';
                        }
                        
                        var iconSvg = iconWrap.querySelector('svg');
                        if (iconSvg) { iconSvg.setAttribute('width', sizeVal); iconSvg.setAttribute('height', sizeVal); }
                        
                        var iconImg = iconWrap.querySelector('img');
                        if (iconImg) {
                            if (viewMode === 'stacked' || viewMode === 'framed' || viewMode === 'square') {
                                iconImg.style.width = '100%'; iconImg.style.height = '100%';
                            } else {
                                iconImg.style.width = sizeVal + 'px';
                            }
                        }
                        if (viewMode === 'stacked' || viewMode === 'framed') {
                            
                            if (s.padding !== undefined) iconWrap.style.padding = parseInt(s.padding) + 'px';
                            if (s.border_radius !== undefined) iconWrap.style.borderRadius = parseInt(s.border_radius) + '%';
                            if (viewMode === 'stacked') {
                                iconWrap.style.background = s.bg_color || ''+ImpC.text+'';
                                iconWrap.style.border = '';
                            } else {
                                iconWrap.style.background = '';
                                if (s.bg_color) iconWrap.style.borderColor = s.bg_color;
                                if (s.border_width !== undefined) iconWrap.style.borderWidth = parseInt(s.border_width) + 'px';
                            }
                        } else {
                            
                            iconWrap.style.padding = '';
                            iconWrap.style.borderRadius = '';
                            iconWrap.style.background = '';
                            iconWrap.style.border = '';
                        }
                    }
                    
                    var titleEl = doc.querySelector(sel + ' .impulse-icon-title');
                    if (titleEl) {
                        if (s.title_content !== undefined) titleEl.innerHTML = s.title_content;
                        if (s.title_size !== undefined) titleEl.style.fontSize = parseInt(s.title_size) + 'px';
                        if (s.title_color) titleEl.style.color = s.title_color;
                    }
                    
                    var textEl = doc.querySelector(sel + ' .impulse-icon-text');
                    if (textEl) {
                        if (s.text_content !== undefined) textEl.innerHTML = s.text_content;
                        if (s.text_size !== undefined) textEl.style.fontSize = parseInt(s.text_size) + 'px';
                        if (s.text_color) textEl.style.color = s.text_color;
                    }
                    
                    var contentEl = doc.querySelector(sel + ' .impulse-icon-content');
                    if (contentEl && s.text_align) {
                        contentEl.style.textAlign = s.text_align;
                    }
                    
                    var iconContainer = doc.querySelector(sel + ' .impulse-icon');
                    if (iconContainer) {
                        if (s.text_spacing !== undefined) iconContainer.style.gap = parseInt(s.text_spacing) + 'px';
                        if (s.container_bg && s.container_bg !== 'transparent') iconContainer.style.background = s.container_bg;
                        if (s.valign) {
                            var valignMap = {top:'flex-start',center:'center',bottom:'flex-end'};
                            iconContainer.style.alignItems = valignMap[s.valign] || 'center';
                        }
                    }
                    
                    var alignWrap = doc.querySelector(sel + ' > div');
                    if (alignWrap && s.align) {
                        alignWrap.style.textAlign = s.align;
                    }
                    
                    var ibContainer = doc.querySelector(sel + ' .impulse-icon');
                    if (ibContainer) {
                        var iconDepth = parseInt(s.ib_icon_depth) || 0;
                        var titleDepth = parseInt(s.ib_title_depth) || 0;
                        var textDepth = parseInt(s.ib_text_depth) || 0;
                        var perspVal = parseInt(s.ib_perspective) || 800;
                        var hasAnyDepth = iconDepth !== 0 || titleDepth !== 0 || textDepth !== 0;
                        if (hasAnyDepth) {
                            ibContainer.style.perspective = perspVal + 'px';
                            ibContainer.style.transformStyle = 'preserve-3d';
                            ibContainer.dataset.ibPerspective = perspVal;
                        } else {
                            ibContainer.style.perspective = '';
                            ibContainer.style.transformStyle = '';
                        }

                        var dofEnabled = !!s.ib_dof;
                        var chromEnabled = !!s.ib_chromatic;
                        var dofVal = dofEnabled ? (parseInt(s.ib_dof_intensity) || 50) / 100 : 0;
                        var chromVal = chromEnabled ? (parseInt(s.ib_chromatic_intensity) || 30) / 100 : 0;
                        var depths = [iconDepth, titleDepth, textDepth];
                        var maxAbsDepth = Math.max.apply(null, depths.map(Math.abs)) || 0;

                        function applyIbLayer(layerEl, z) {
                            if (!layerEl) return;
                            layerEl.dataset.depth = z;
                            layerEl.style.transformStyle = 'preserve-3d';
                            layerEl.style.transform = 'translateZ(' + z + 'px)';
                            var absRatio = maxAbsDepth > 0 ? Math.abs(z) / maxAbsDepth : 0;
                            var signedRatio = maxAbsDepth > 0 ? z / maxAbsDepth : 0;
                            var isIcon = layerEl.classList.contains('impulse-icon-wrap');
                            if (chromVal > 0) {
                                var offset = chromVal * 5;
                                var r = (signedRatio * offset).toFixed(1);
                                var b = (-signedRatio * offset).toFixed(1);
                                var alpha = (chromVal * 0.4).toFixed(2);
                                if (isIcon) {
                                    var filters = [];
                                    if (dofVal > 0) filters.push('blur(' + (absRatio * dofVal * 5).toFixed(1) + 'px)');
                                    filters.push('drop-shadow(' + r + 'px 0 0 rgba(255,0,50,' + alpha + '))');
                                    filters.push('drop-shadow(' + b + 'px 0 0 rgba(0,80,255,' + alpha + '))');
                                    layerEl.style.filter = filters.join(' ');
                                    layerEl.style.textShadow = '';
                                } else {
                                    layerEl.style.filter = dofVal > 0 ? 'blur(' + (absRatio * dofVal * 5).toFixed(1) + 'px)' : '';
                                    layerEl.style.textShadow = r + 'px 0 0 rgba(255,0,50,' + alpha + '),' + b + 'px 0 0 rgba(0,80,255,' + alpha + ')';
                                }
                            } else if (dofVal > 0) {
                                layerEl.style.filter = 'blur(' + (absRatio * dofVal * 5).toFixed(1) + 'px)';
                                layerEl.style.textShadow = '';
                            } else {
                                layerEl.style.filter = '';
                                layerEl.style.textShadow = '';
                            }
                        }

                        applyIbLayer(doc.querySelector(sel + ' .impulse-icon-wrap'), iconDepth);
                        applyIbLayer(doc.querySelector(sel + ' .impulse-icon-title'), titleDepth);
                        applyIbLayer(doc.querySelector(sel + ' .impulse-icon-text'), textDepth);
                    }
                }
            }

            if (type === 'social') {
                var prev = window.socialPrev || {};
                if (JSON.stringify(prev.links) !== JSON.stringify(settings.links) ||
                    prev.bg_shape !== settings.bg_shape ||
                    prev.hover_effect !== settings.hover_effect ||
                    !!prev.brand_colors !== !!settings.brand_colors) {
                    window.socialPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.socialPrev = JSON.parse(JSON.stringify(settings));
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var s = resolvedSettings;
                    
                    if (s.icon_color && !s.brand_colors) css += sel + ' .impulse-social-icons svg{color:' + s.icon_color + '!important}';
                    
                    if (s.bg_color && s.bg_shape && s.bg_shape !== 'none') css += sel + ' .impulse-social-icons a{background:' + s.bg_color + '!important}';
                    
                    if (s.hover_color) css += sel + ' .impulse-social-icons a:hover svg{color:' + s.hover_color + '!important}';
                    if (css) {
                        var styleId = 'impulse-live-social-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
                
            }
                        
            if (type === 'table') {
                var prev = window.iconListPrev || {};
                var prevHasAnim = prev.entrance_animation && prev.entrance_animation !== 'none';
                var curHasAnim = settings.entrance_animation && settings.entrance_animation !== 'none';

                
                
                function _ilOn(v, def)  { if (v === undefined) return !!def; return !!v && v !== '0'; }
                var prev_sh  = _ilOn(prev.show_header, true),  cur_sh  = _ilOn(settings.show_header, true);
                var prev_si  = _ilOn(prev.show_icons,  true),  cur_si  = _ilOn(settings.show_icons,  true);
                var prev_zb  = _ilOn(prev.zebra_stripes, false), cur_zb = _ilOn(settings.zebra_stripes, false);
                if (JSON.stringify(prev.items) !== JSON.stringify(settings.items) ||
                    (!!prev.stagger_items !== !!settings.stagger_items && curHasAnim) ||
                    (!!settings.stagger_items && prevHasAnim !== curHasAnim) ||
                    prev_sh !== cur_sh ||
                    prev_si !== cur_si ||
                    prev_zb !== cur_zb) {
                    window.iconListPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.iconListPrev = JSON.parse(JSON.stringify(settings));
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var elNode = doc.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (elNode) {
                        var ul = elNode.querySelector('.impulse-table');
                        if (ul) {
                            var hh = !!settings.hover_highlight;
                            ul.classList.toggle('impulse-table-hover', hh);
                            ul.classList.remove('impulse-hh-slide', 'impulse-hh-glow', 'impulse-hh-lift');
                            if (hh) {
                                var eff = settings.hover_highlight_effect || 'subtle';
                                if (eff !== 'subtle') ul.classList.add('impulse-hh-' + eff);
                            }
                            var lis = ul.querySelectorAll('li');
                            for (var li = 0; li < lis.length; li++) {
                                if (hh) {
                                    lis[li].style.padding = '6px 8px';
                                    lis[li].style.borderRadius = '4px';
                                    lis[li].style.margin = '0 -8px';
                                } else {
                                    lis[li].style.padding = '';
                                    lis[li].style.borderRadius = '';
                                    lis[li].style.margin = '';
                                }
                            }
                        }
                    }
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var mw = parseInt(settings.section_max_width);
                    if (mw > 0) {
                        css += sel + '{max-width:' + mw + 'px!important;margin-left:auto!important;margin-right:auto!important}';
                    }
                    if (!!settings.hover_highlight) {
                        var hhDur = (parseInt(settings.hh_duration) || 200) / 1000;
                        css += sel + ' .impulse-table li{transition:background ' + hhDur + 's ease-in-out,transform ' + hhDur + 's ease-in-out,box-shadow ' + hhDur + 's ease-in-out!important}';
                        if ((settings.hover_highlight_effect || 'subtle') === 'slide') {
                            css += sel + ' .impulse-hh-slide li::before{transition:transform ' + hhDur + 's ease-in-out!important}';
                        }
                    }
                    var styleId = 'impulse-live-il-' + id;
                    var existing = doc.getElementById(styleId);
                    if (existing) existing.remove();
                    if (css) {
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
            }

            
            if (type === 'price_list') {
                var prev = window.priceListPrev || {};
                window.priceListPrev = JSON.parse(JSON.stringify(settings));
                if (JSON.stringify(prev.pl_items) !== JSON.stringify(settings.pl_items) ||
                    prev.pl_separator !== settings.pl_separator) {
                    return 'needs-refresh';
                }
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var showDiv = settings.pl_show_divider;
                    if (showDiv === '0' || showDiv === 0 || showDiv === false || showDiv === '') {
                        css += sel + ' .impulse-price-item { border-bottom: none !important; }';
                    }
                    var mw = parseInt(settings.section_max_width);
                    if (mw > 0) {
                        css += sel + ' { max-width:' + mw + 'px !important; margin-left:auto !important; margin-right:auto !important; }';
                    }
                    var styleId = 'impulse-live-pl-' + id;
                    var existing = doc.getElementById(styleId);
                    if (existing) existing.remove();
                    if (css) {
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
            }

            if (type === 'modal') {
                var prev = window.offCanvasPrev || {};
                window.offCanvasPrev = JSON.parse(JSON.stringify(settings));
                if (prev.oc_position !== settings.oc_position ||
                    !!prev.oc_show_close !== !!settings.oc_show_close ||
                    !!prev.oc_show_overlay !== !!settings.oc_show_overlay ||
                    !!prev.oc_close_on_overlay !== !!settings.oc_close_on_overlay) {
                    return 'needs-refresh';
                }
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var s = resolvedSettings;
                    var panelSel = sel + ' .impulse-modal-drawer-preview';
                    var panelCss = '';
                    if (s.oc_bg) panelCss += 'background-color:' + s.oc_bg + '!important;';
                    if (s.oc_width !== undefined) panelCss += 'width:' + parseInt(s.oc_width) + 'px!important;max-width:' + parseInt(s.oc_width) + 'px!important;';
                    if (s.oc_padding !== undefined) panelCss += 'padding:' + parseInt(s.oc_padding) + 'px!important;';
                    if (panelCss) css += panelSel + '{' + panelCss + '}';
                    if (s.oc_overlay_color) css += sel + ' .impulse-modal-drawer-overlay{background-color:' + s.oc_overlay_color + '!important}';
                    if (css) {
                        var styleId = 'impulse-live-oc-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
            }

            
            if (type === 'unfold') {
                var prev = window.unfoldPrev || {};
                
                if (JSON.stringify(prev.items) !== JSON.stringify(settings.items) ||
                    prev.allow_multiple !== settings.allow_multiple ||
                    prev.first_open !== settings.first_open ||
                    prev.unfold_icon !== settings.unfold_icon ||
                    prev.anim_style !== settings.anim_style) {
                    window.unfoldPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.unfoldPrev = JSON.parse(JSON.stringify(settings));
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var s = resolvedSettings;
                    var aStyle = s.anim_style || 'spotlight';
                    var isScrollM = (aStyle === 'rolodex');

                    if (aStyle === 'spotlight') {
                        if (s.spot_bg)        css += sel + ' .impulse-acc-spotlight{background:' + s.spot_bg + '!important}';
                        if (s.header_color)   css += sel + ' .impulse-acc-spot-header{color:' + s.header_color + '!important}';
                        if (s.content_bg)     css += sel + ' .impulse-acc-spot-item.active{background:' + s.content_bg + '!important}';
                        if (s.content_color)  css += sel + ' .impulse-acc-spot-body{color:' + s.content_color + '!important}';
                        if (s.accent_color)   css += sel + ' .impulse-acc-spot-item.active .impulse-acc-spot-header{color:' + s.accent_color + '!important}';
                        if (s.border_radius !== undefined) css += sel + ' .impulse-acc-spotlight,' + sel + ' .impulse-acc-spot-item.active{border-radius:' + parseInt(s.border_radius) + 'px!important}';
                        if (s.blur_intensity !== undefined) {
                            var bl = parseFloat(s.blur_intensity) || 0;
                            css += sel + ' .impulse-acc-spot-item:not(.active){filter:blur(' + bl + 'px)!important}';
                        }
                    }
                    
                    if (s.title_size !== undefined) {
                        var ts = parseInt(s.title_size);
                        css += sel + ' .impulse-acc-spot-header span:first-child{font-size:' + ts + 'px!important}';
                        css += sel + ' .impulse-unfold-card-title{font-size:' + ts + 'px!important}';
                    }
                    if (s.content_size !== undefined) {
                        var cs2 = parseInt(s.content_size);
                        css += sel + ' .impulse-acc-spot-body{font-size:' + cs2 + 'px!important}';
                        css += sel + ' .impulse-unfold-card > div:last-child{font-size:' + cs2 + 'px!important}';
                    }
                    if (css) {
                        var styleId = 'impulse-live-unfold-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
            }

            if (type === 'modal') {
                var prev = window.popupPrev || {};
                
                var prevClose = prev.show_close === false || prev.show_close === '0' || prev.show_close === 0 ? false : true;
                var curClose = settings.show_close === false || settings.show_close === '0' || settings.show_close === 0 ? false : true;
                if (prevClose !== curClose) {
                    window.popupPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.popupPrev = JSON.parse(JSON.stringify(settings));
                
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var css = '';
                    var s = resolvedSettings;

                    

                    

                    var cSel = sel + ' .impulse-modal-container';
                    if (s.popup_bg) css += cSel + '{background:' + s.popup_bg + '!important}';
                    if (s.popup_radius !== undefined) css += cSel + '{border-radius:' + parseInt(s.popup_radius) + 'px!important}';
                    
                    var _padLegacy = s.popup_padding !== undefined && s.popup_padding !== '' ? parseInt(s.popup_padding) : null;
                    var _padH = s.popup_padding_h !== undefined && s.popup_padding_h !== '' ? parseInt(s.popup_padding_h)
                              : (_padLegacy !== null ? _padLegacy : null);
                    var _padV = s.popup_padding_v !== undefined && s.popup_padding_v !== '' ? parseInt(s.popup_padding_v)
                              : (_padLegacy !== null ? _padLegacy : null);
                    if (_padH !== null || _padV !== null) {
                        var _vh = (_padV !== null && !isNaN(_padV)) ? _padV : 24;
                        var _hh = (_padH !== null && !isNaN(_padH)) ? _padH : 24;
                        css += cSel + '{padding:' + _vh + 'px ' + _hh + 'px!important}';
                    }
                    if (s.popup_height !== undefined) css += cSel + '{min-height:' + (parseInt(s.popup_height) || 0) + 'px!important}';
                    if (s.popup_content_gap !== undefined) {
                        var _cg = parseInt(s.popup_content_gap);
                        if (!isNaN(_cg)) css += cSel + ' .impulse-modal-content{gap:' + _cg + 'px!important}';
                    }
                    if (css) {
                        var styleId = 'impulse-live-popup-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
                
                if (!window._impulsePrevSettings) window._impulsePrevSettings = {};
                window._impulsePrevSettings[id] = JSON.stringify(stripEntrance(settings));
            }

            if (type === 'plans') {
                var prev = window.pricingPrev || {};
                window.pricingPrev = JSON.parse(JSON.stringify(settings));
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"]';
                    var s = resolvedSettings;
                    var toggleWrap = doc.querySelector(sel + ' .impulse-plans-toggle-wrap');
                    if (toggleWrap) toggleWrap.style.display = s.show_toggle ? '' : 'none';
                    var plansWrap = doc.querySelector(sel + ' .impulse-plans');
                    if (plansWrap && s.ribbon_style) plansWrap.setAttribute('data-ribbon', s.ribbon_style);
                    doc.querySelectorAll(sel + ' .impulse-plan-card').forEach(function(c) {
                        if (s.hover_effect) c.setAttribute('data-hover', s.hover_effect);
                    });

                    
                    var _arcIntensity = Math.max(0, Math.min(100, parseInt(s.arc_intensity) || 0));
                    var _arcGrid = doc.querySelector(sel + ' .impulse-pricing-grid');
                    var _arcCards = _arcGrid ? _arcGrid.querySelectorAll(':scope > .impulse-pricing-card') : [];
                    if (_arcGrid && _arcCards.length > 1) {
                        var _arcActive = _arcIntensity > 0;
                        if (_arcActive) {
                            _arcGrid.classList.add('impulse-pricing-arc');
                            _arcGrid.style.perspective = '1200px';
                            _arcGrid.style.perspectiveOrigin = 'center top';
                            _arcGrid.style.transformStyle = 'preserve-3d';

                            var _arcStyleId = 'impulse-plans-arc-' + id;
                            if (!doc.getElementById(_arcStyleId)) {
                                var _arcStyle = doc.createElement('style');
                                _arcStyle.id = _arcStyleId;
                                _arcStyle.textContent = sel + ' .impulse-pricing-arc .impulse-pricing-card{transform-origin:center top;backface-visibility:hidden;transition:transform 0.35s cubic-bezier(0.4, 0, 0.2, 1);will-change:transform}'
                                    + sel + ' .impulse-pricing-arc .impulse-pricing-card:hover{transform:rotateY(0) !important}'
                                    + '@media(max-width:768px){' + sel + ' .impulse-pricing-arc{perspective:none !important}' + sel + ' .impulse-pricing-arc .impulse-pricing-card{transform:none !important}}';
                                if (doc.head) doc.head.appendChild(_arcStyle);
                            }
                        } else {
                            _arcGrid.classList.remove('impulse-pricing-arc');
                            _arcGrid.style.perspective = '';
                            _arcGrid.style.perspectiveOrigin = '';
                            _arcGrid.style.transformStyle = '';
                        }
                        var _arcCenterIdx = (_arcCards.length - 1) / 2.0;
                        var _arcMaxAngle = 25.0;
                        var _arcScale = _arcIntensity / 100.0;
                        _arcCards.forEach(function(card, i) {
                            if (!_arcActive || _arcCenterIdx <= 0) {
                                card.style.transform = '';
                                card.removeAttribute('data-arc-base');
                                card.removeAttribute('data-arc-hover');
                                return;
                            }
                            var _relPos = (_arcCenterIdx - i) / _arcCenterIdx;
                            var _angle  = Math.round(_relPos * _arcMaxAngle * _arcScale * 100) / 100;

                            
                            card.setAttribute('data-arc-base', _angle);
                        });
                        
                        if (_arcGrid._impulseArcRefresh) _arcGrid._impulseArcRefresh();
                    }
                }
                if (JSON.stringify(prev.plans) !== JSON.stringify(settings.plans)) {
                    return 'needs-refresh';
                }
            }

            
            if (type === 'booking') {
                var prev = window.bookingBlockPrev || {};

                window.bookingBlockPrev = JSON.parse(JSON.stringify(settings));
                var _bDoc = window.impulseCSSVars.getDoc();
                if (_bDoc) {
                    var _bSel = '.impulse-el[data-id="' + id + '"] .impulse-booking-block';
                    var _bH2 = _bDoc.querySelector(_bSel + ' h2');
                    if (_bH2 && settings.title !== undefined) _bH2.textContent = settings.title || '';
                    _bDoc.querySelectorAll(_bSel + ' .ibk-next-btn,' + _bSel + ' .ibk-submit-btn').forEach(function(b) {
                        if (settings.button_text !== undefined) b.textContent = settings.button_text || 'Continue';
                    });
                }

                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var sel = '.impulse-el[data-id="' + id + '"] .impulse-booking-block';
                    var s = resolvedSettings;
                    var css = '';
                    
                    if (s.title_size !== undefined) css += sel + ' h2 { font-size:' + parseInt(s.title_size) + 'px !important; }';
                    
                    if (s.max_width !== undefined) css += sel + ' { max-width:' + parseInt(s.max_width) + 'px !important; }';
                    
                    if (s.button_bg) css += sel + ' .ibk-next-btn, ' + sel + ' .ibk-submit-btn { background:' + s.button_bg + ' !important; border-color:' + s.button_bg + ' !important; }';
                    if (s.button_color) css += sel + ' .ibk-next-btn, ' + sel + ' .ibk-submit-btn { color:' + s.button_color + ' !important; }';
                    
                    if (s.button_radius !== undefined) css += sel + ' .ibk-next-btn, ' + sel + ' .ibk-submit-btn, ' + sel + ' .ibk-back-btn { border-radius:' + parseInt(s.button_radius) + 'px !important; }';
                    
                    if (s.field_bg) css += sel + ' select, ' + sel + ' input, ' + sel + ' textarea { background:' + s.field_bg + ' !important; }';
                    if (s.field_border) css += sel + ' select, ' + sel + ' input, ' + sel + ' textarea { border-color:' + s.field_border + ' !important; }' + sel + ' .ibk-cal-grid button:not(:disabled):not(.ibk-selected-day) { border-color:' + s.field_border + ' !important; background:' + s.field_bg + ' !important; }' + sel + ' .ibk-slots-grid button:not(:disabled):not(.ibk-selected-slot) { border-color:' + s.field_border + ' !important; background:' + s.field_bg + ' !important; }';
                    
                    if (s.field_radius !== undefined) {
                        var fr = parseInt(s.field_radius);
                        css += sel + ' select, ' + sel + ' input:not([type="hidden"]), ' + sel + ' textarea, ' + sel + ' .ibk-cal-grid button, ' + sel + ' .ibk-slots-grid button { border-radius:' + fr + 'px !important; }';
                    }
                    if (css) {
                        var styleId = 'impulse-live-booking-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }
            }

            if (type === 'contact') {
                var prev = window.formPrev || {};
                window.formPrev = JSON.parse(JSON.stringify(settings));
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var _cSel = '.impulse-el[data-id="' + id + '"]';
                    var _cBtn = doc.querySelector(_cSel + ' .impulse-contact-submit');
                    if (_cBtn && settings.button_text !== undefined) _cBtn.textContent = settings.button_text || 'Submit';
                    doc.querySelectorAll(_cSel + ' .impulse-form-label').forEach(function(l) {
                        l.style.display = settings.show_labels ? '' : 'none';
                    });

                    
                    if (settings.show_placeholders !== undefined) {
                        doc.querySelectorAll(_cSel + ' input:not([type=hidden]),' + _cSel + ' textarea,' + _cSel + ' select').forEach(function(inp) {
                            if (!inp._origPH) inp._origPH = inp.getAttribute('placeholder') || '';
                            inp.setAttribute('placeholder', settings.show_placeholders ? inp._origPH : '');
                        });
                    }

                    

                    
                    
                    var _lblCss = '';
                    if (settings.field_label_color !== undefined && settings.field_label_color !== '') {
                        var _lblC = String(settings.field_label_color);
                        _lblCss = _cSel + ' .impulse-form input::placeholder,'
                                + _cSel + ' .impulse-form textarea::placeholder,'
                                + _cSel + ' .impulse-form select::placeholder,'

                                
                                + _cSel + ' .impulse-form .impulse-form-dropdown-value.is-placeholder{color:' + _lblC + '!important;opacity:1!important}'
                                + _cSel + ' .impulse-form-field > label{color:' + _lblC + '!important}';
                    }
                    var _styleId = 'impulse-live-contact-label-' + id;
                    var _existing = doc.getElementById(_styleId);
                    if (_lblCss) {
                        if (!_existing) {
                            _existing = doc.createElement('style');
                            _existing.id = _styleId;
                            doc.head.appendChild(_existing);
                        }
                        _existing.textContent = _lblCss;
                    } else if (_existing) {
                        _existing.remove();
                    }
                }
                if (JSON.stringify(prev.fields) !== JSON.stringify(settings.fields) ||
                    prev.on_submit !== settings.on_submit ||
                    prev.section_max_width !== settings.section_max_width) {
                    return 'needs-refresh';
                }
            }

            if (type === 'title') {
                var prev = window.displayTextPrev || {};
                window.displayTextPrev = JSON.parse(JSON.stringify(settings));
                if (!Object.keys(prev).length) return;
                
                if ((prev.tag || 'h2') !== (settings.tag || 'h2')) return 'needs-refresh';
                
                var prevHas = (prev.line_1||'').trim() !== '';
                var curHas  = (settings.line_1||'').trim() !== '';
                if (prevHas !== curHas) return 'needs-refresh';
            }

            if (type === 'header') {
                var prev = window.siteHeaderPrev || {};
                window.siteHeaderPrev = JSON.parse(JSON.stringify(settings));
                
                if (!Object.keys(prev).length) return;
                if (JSON.stringify(prev) !== JSON.stringify(settings)) {
                    
                    var headerStructuralKeys = ['layout','logo','menu_items','menu_position','sticky','sticky_mode','header_bg','show_cart','show_account','show_site_name','site_name','announcement_enabled','announcement_text','announcement_link','show_breadcrumbs','show_cta','cta_text','cta_url','cart_url','account_url'];
                    var needsRefresh = false;
                    for (var k in settings) {
                        if (settings[k] !== prev[k]) {
                            var baseKey = k.replace(/_tablet$|_mobile$/, '');
                            if (headerStructuralKeys.indexOf(baseKey) !== -1) {
                                needsRefresh = true;
                                break;
                            }
                        }
                    }
                    for (var k in prev) {
                        if (prev[k] !== settings[k]) {
                            var baseKey = k.replace(/_tablet$|_mobile$/, '');
                            if (headerStructuralKeys.indexOf(baseKey) !== -1) {
                                needsRefresh = true;
                                break;
                            }
                        }
                    }
                    if (needsRefresh) {
                        return 'needs-refresh';
                    }
                    
                    var doc = window.impulseCSSVars.getDoc();
                    if (doc) {
                        var styleId = 'impulse-header-live';
                        var existing = doc.getElementById(styleId);
                        if (!existing) {
                            existing = doc.createElement('style');
                            existing.id = styleId;
                            if (doc.head) doc.head.appendChild(existing);
                        }
                        var s = resolvedSettings;
                        var bgColor = s.bg_color || '#ffffff';
                        var textColor = s.text_color || ''+ImpC.surface2+'';
                        var hoverColor = s.hover_color || '#666666';
                        var borderColor = s.border_color || ''+ImpC.text+'';
                        var borderWidth = parseInt(s.border_width) || 1;
                        var logoH = parseInt(s.logo_height) || 40;
                        var showBorder = s.show_border !== false && s.show_border !== '0' && s.show_border !== 0;
                        var showShadow = s.show_shadow === true || s.show_shadow === '1' || s.show_shadow === 1;
                        var padTop = parseInt(s.padding_top) || 16;
                        var padBottom = parseInt(s.padding_bottom) || 16;
                        var sidePad = parseInt(s.side_padding) || 40;
                        var menuGap = parseInt(s.menu_gap) || 32;
                        var menuFontSize = parseInt(s.menu_font_size) || 15;
                        var iconSize = parseInt(s.icon_size) || 20;
                        var annBg = s.announcement_bg || ''+ImpC.surface2+'';
                        var annColor = s.announcement_text_color || '#ffffff';
                        var css = '.impulse-header .impulse-header-main{background:' + bgColor + '!important;padding-top:' + padTop + 'px!important;padding-bottom:' + padBottom + 'px!important;padding-left:' + sidePad + 'px!important;padding-right:' + sidePad + 'px!important;border-bottom:' + (showBorder ? borderWidth + 'px solid ' + borderColor : 'none') + '!important;box-shadow:' + (showShadow ? '0 2px 8px rgba(0,0,0,0.15)' : 'none') + '!important}';
                        css += '.impulse-header .impulse-header-main a,.impulse-header .impulse-header-menu a,.impulse-header .impulse-header-icons svg{color:' + textColor + '!important;stroke:' + textColor + '!important}';
                        css += '.impulse-header .impulse-header-menu a:hover{color:' + hoverColor + '!important}';
                        css += '.impulse-header .impulse-header-logo img{height:' + logoH + 'px!important}';
                        css += '.impulse-header .impulse-header-menu{gap:' + menuGap + 'px!important}';
                        css += '.impulse-header .impulse-header-menu a{font-size:' + menuFontSize + 'px!important}';
                        css += '.impulse-header .impulse-header-icons svg{width:' + iconSize + 'px!important;height:' + iconSize + 'px!important}';
                        css += '.impulse-header .impulse-header-icons{right:' + sidePad + 'px!important}';
                        css += '.impulse-announcement-bar{background:' + annBg + '!important;color:' + annColor + '!important}';
                        css += '.impulse-announcement-bar a{color:' + annColor + '!important}';
                        existing.textContent = css;
                    }
                    return;
                }
            }

            if (type === 'footer') {
                var prev = window.siteFooterPrev || {};
                window.siteFooterPrev = JSON.parse(JSON.stringify(settings));
                if (!Object.keys(prev).length) return;
                if (JSON.stringify(prev) !== JSON.stringify(settings)) {
                    
                    var footerStructuralKeys = ['layout','logo','site_name','description','copyright_text','social_links','menu_id','show_logo','show_description','show_social','show_copyright'];
                    var needsRefresh = false;
                    for (var k in settings) {
                        if (settings[k] !== prev[k]) {
                            var baseKey = k.replace(/_tablet$|_mobile$/, '');
                            
                            if (footerStructuralKeys.indexOf(baseKey) !== -1 || baseKey.indexOf('_link_label') !== -1 || baseKey.indexOf('_link_url') !== -1 || baseKey.indexOf('_title') !== -1) {
                                needsRefresh = true;
                                break;
                            }
                        }
                    }
                    for (var k in prev) {
                        if (prev[k] !== settings[k]) {
                            var baseKey = k.replace(/_tablet$|_mobile$/, '');
                            if (footerStructuralKeys.indexOf(baseKey) !== -1 || baseKey.indexOf('_link_label') !== -1 || baseKey.indexOf('_link_url') !== -1 || baseKey.indexOf('_title') !== -1) {
                                needsRefresh = true;
                                break;
                            }
                        }
                    }
                    if (needsRefresh) {
                        return 'needs-refresh';
                    }
                    
                    var doc = window.impulseCSSVars.getDoc();
                    if (doc) {
                        var styleId = 'impulse-footer-live';
                        var existing = doc.getElementById(styleId);
                        if (!existing) {
                            existing = doc.createElement('style');
                            existing.id = styleId;
                            if (doc.head) doc.head.appendChild(existing);
                        }
                        var s = resolvedSettings;
                        var bgColor = s.bg_color || ''+ImpC.surface+'';
                        var textColor = s.text_color || '#999999';
                        var headingColor = s.heading_color || '#ffffff';
                        var linkColor = textColor;
                        var linkHoverColor = headingColor;
                        var padTop = parseInt(s.padding_top) || 60;
                        var css = '.impulse-footer{background:' + bgColor + '!important;color:' + textColor + '!important;padding:' + padTop + 'px 40px ' + Math.max(Math.round(padTop*0.5),20) + 'px 40px!important}';
                        css += '.impulse-footer a{color:' + linkColor + '!important}';
                        css += '.impulse-footer a:hover{color:' + linkHoverColor + '!important}';
                        css += '.impulse-footer [style*="font-weight:600"],.impulse-footer [style*="font-weight:700"]{color:' + headingColor + '!important}';
                        existing.textContent = css;
                    }
                    return;
                }
            }

            
            if (type === 'checkout') {
                var prev = window.checkoutPrev || {};
                if (JSON.stringify(prev.checkout_design_fields) !== JSON.stringify(settings.checkout_design_fields) ||
                    prev.checkout_design_guest_checkout !== settings.checkout_design_guest_checkout ||
                    prev.checkout_design_create_account !== settings.checkout_design_create_account ||
                    prev.checkout_design_email_first !== settings.checkout_design_email_first ||
                    prev.checkout_design_show_coupon !== settings.checkout_design_show_coupon ||
                    prev.checkout_design_show_gift_card !== settings.checkout_design_show_gift_card) {
                    window.checkoutPrev = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.checkoutPrev = JSON.parse(JSON.stringify(settings));
            }

            
            if (type === 'products') {
                
                var dm = settings.display_mode || 'grid';
                var renderType = dm === 'carousel' ? 'product_carousel' : (dm === 'single' ? 'product_single' : 'products');
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return 'needs-refresh';

                if (renderType === 'product_carousel' || renderType === 'product_single') {
                    var elSel3 = '.impulse-el[data-id="' + id + '"]';
                    var doc3 = iframe.contentDocument;
                    var car3 = doc3.querySelector(elSel3 + ' .impulse-product-carousel');
                    var css3 = '';
                    
                    if (settings.transition_speed !== undefined) {
                        css3 += elSel3 + ' .impulse-carousel-slides{transition-duration:' + settings.transition_speed + 'ms!important}';
                        if (car3) {
                            car3.dataset.transition = settings.transition_speed;
                            car3.dispatchEvent(new CustomEvent('impulse:transition-change'));
                        }
                    }

                    var carouselMode3 = (car3 && car3.dataset.mode) || settings.carousel_mode || 'snap';
                    var isSingleEffect3 = dm === 'single' || ['fade','card_flip'].indexOf(carouselMode3) !== -1;
                    
                    var carMode3 = (car3 && car3.dataset.mode) || settings.carousel_mode || 'snap';
                    if (!isSingleEffect3 && carMode3 === 'scroll' && settings.card_carousel_width !== undefined) {
                        var cw4 = Math.max(150, Math.min(500, parseInt(settings.card_carousel_width) || 250));
                        css3 += elSel3 + ' .impulse-carousel-slide{flex:0 0 ' + cw4 + 'px!important;min-width:' + cw4 + 'px!important;max-width:' + cw4 + 'px!important}';
                        if (car3) car3.dataset.cardWidth = cw4;
                    }

                    
                    
                    if (isSingleEffect3) {
                        var cwKey3 = device !== 'desktop' ? 'card_max_width_' + device : 'card_max_width';
                        var cwBase3 = parseInt(settings[cwKey3] !== undefined ? settings[cwKey3] : settings.card_max_width) || 250;
                        var cw3 = Math.max(250, Math.min(500, cwBase3));
                        css3 += elSel3 + ' .impulse-carousel-slides{width:' + cw3 + 'px!important;max-width:' + cw3 + 'px!important;min-width:' + cw3 + 'px!important}';
                    }
                    
                    var badgeBgInput = document.querySelector('input[name="card_design_sale_badge_bg_color"]');
                    var badgeFeaturedBgInput = document.querySelector('input[name="card_design_featured_badge_bg_color"]');
                    var badgeTxtInput = document.querySelector('input[name="card_design_sale_badge_text_color"]');
                    if (badgeBgInput && badgeBgInput.value) {
                        css3 += elSel3 + ' .impulse-pcard{--badge-bg:' + badgeBgInput.value + '!important}';
                    }
                    if (badgeFeaturedBgInput && badgeFeaturedBgInput.value) {
                        css3 += elSel3 + ' .impulse-pcard{--featured-badge-bg:' + badgeFeaturedBgInput.value + '!important}';
                    }
                    if (badgeTxtInput && badgeTxtInput.value) {
                        css3 += elSel3 + ' .impulse-pcard{--badge-txt:' + badgeTxtInput.value + '!important}';
                    }

                    

                    

                    

                    var _flipEff = settings.flip_card_effect || '';
                    if (_flipEff) {
                        var _pfc = 'pfc-' + String(_flipEff).replace(/_/g, '-').replace(/[^a-z-]/g, '');
                        doc3.querySelectorAll(elSel3 + ' .impulse-flip-card').forEach(function (fc) {
                            var keep = [];
                            fc.className.split(/\s+/).forEach(function (c) {
                                if (c && c.indexOf('pfc-') !== 0) keep.push(c);
                            });
                            keep.push(_pfc);
                            fc.className = keep.join(' ');
                            fc.dataset.flipEffect = _pfc.slice(4);
                        });
                    }
                    
                    if (settings.autoplay_speed !== undefined && car3) {
                        car3.dataset.speed = Math.max(1000, parseInt(settings.autoplay_speed) * 1000);
                        car3.dispatchEvent(new CustomEvent('impulse:speed-change'));
                    }
                    if (css3) {
                        var sEl3 = doc3.getElementById('impulse-live-pc-' + id);
                        if (!sEl3) { sEl3 = doc3.createElement('style'); sEl3.id = 'impulse-live-pc-' + id; doc3.head && doc3.head.appendChild(sEl3); }
                        sEl3.textContent = css3;
                    }
                }
                
                var css = '';
                var elSelector = '.impulse-el[data-id="' + id + '"]';
                
                var cardSelector = elSelector + ' .impulse-pcard';

                var cardDesign = settings.card_design || {};
                var card = cardDesign.card || {};

                var borderRadius = card.border_radius !== undefined ? card.border_radius : 8;
                css += cardSelector + ' { border-radius: ' + borderRadius + 'px !important; }';

                var _borderInput = document.querySelector('input[name="card_design_card_border_width"]');
                var borderWidth = _borderInput ? parseInt(_borderInput.value) : (card.border_width !== undefined ? parseInt(card.border_width) : 0);
                var borderColor = card.border_color || ''+ImpC.text+'';
                css += borderWidth > 0
                    ? cardSelector + ' { border: ' + borderWidth + 'px solid ' + borderColor + ' !important; }'
                    : cardSelector + ' { border: none !important; }';

                var bgColor = card.background || '#ffffff';
                css += cardSelector + ' { background: ' + bgColor + ' !important; }';

                var _shadowInput = document.querySelector('input[name="card_design_card_shadow"]');
                var shadowVal = _shadowInput ? _shadowInput.value : (card.shadow || '');
                var shadowStyles = { none: 'none', small: '0 1px 3px rgba(0,0,0,0.1)', medium: '0 4px 6px rgba(0,0,0,0.1)', large: '0 10px 25px rgba(0,0,0,0.15)' };
                var shadowCss = shadowStyles[shadowVal] || 'none';
                css += cardSelector + ' { box-shadow: ' + shadowCss + ' !important; }';
                
                css += elSelector + ' .impulse-flip-card { box-shadow: ' + shadowCss + ' !important; }';
                css += elSelector + ' .impulse-flip-card .impulse-pcard { box-shadow: none !important; }';

                var device = window.impulseDevice || 'desktop';
                var gapKey = device === 'desktop' ? 'gap' : 'gap_' + device;
                var gapVal = settings[gapKey] !== undefined ? settings[gapKey] : (settings.gap || 10);
                if (renderType === 'products') {
                    css += elSelector + ' .impulse-product-grid { gap: ' + gapVal + 'px !important; }';
                } else {
                    css += elSelector + ' .impulse-carousel-slides { gap: ' + gapVal + 'px !important; }';
                }

                if (settings.section_bg) {
                    if (renderType === 'products') {
                        css += elSelector + ' .impulse-product-grid { background: ' + settings.section_bg + ' !important; }';
                    } else {
                        css += elSelector + ' .impulse-product-carousel { background: ' + settings.section_bg + ' !important; }';
                    }
                }
                
                if (renderType === 'products') {
                    
                    if (device === 'desktop') {
                        
                        var colKeyMW = device === 'desktop' ? 'columns' : 'columns_' + device;
                        var gridCols = parseInt(settings[colKeyMW]) || parseInt(settings.columns) || 4;
                        var colMaxCap = gridCols === 1 ? 500 : gridCols === 2 ? 1000 : gridCols === 3 ? 1500 : 1600;
                        var maxWidth = settings.section_max_width !== undefined ? Math.min(parseInt(settings.section_max_width), colMaxCap) : Math.min(1200, colMaxCap);
                        if (maxWidth > 0) {
                            css += elSelector + ' .impulse-product-grid { max-width: ' + maxWidth + 'px !important; margin-left: auto !important; margin-right: auto !important; }';
                        } else {
                            css += elSelector + ' .impulse-product-grid { max-width: none !important; }';
                        }
                    }
                    
                } else {
                    
                    css += elSelector + ' .impulse-product-carousel { max-width: none !important; width: 100% !important; }';
                }

                var title = cardDesign.title || {};
                var titleFontSize = (device !== 'desktop' && title['font_size_' + device] !== undefined) ? title['font_size_' + device] : title.font_size;
                if (title.color) css += cardSelector + ' .impulse-pcard-title { color: ' + title.color + ' !important; }';
                if (titleFontSize) css += cardSelector + ' .impulse-pcard-title { font-size: ' + titleFontSize + 'px !important; }';
                if (title.font_weight) css += cardSelector + ' .impulse-pcard-title { font-weight: ' + title.font_weight + ' !important; }';

                var price = cardDesign.price || {};
                var priceFontSize = (device !== 'desktop' && price['font_size_' + device] !== undefined) ? price['font_size_' + device] : price.font_size;
                var priceColor = price.color || title.color;
                if (priceColor) css += cardSelector + ' .impulse-pcard-price { color: ' + priceColor + ' !important; }';
                if (priceFontSize) css += cardSelector + ' .impulse-pcard-price { font-size: ' + priceFontSize + 'px !important; }';
                if (price.font_weight) css += cardSelector + ' .impulse-pcard-price, ' + cardSelector + ' .impulse-pcard-price span { font-weight: ' + price.font_weight + ' !important; }';
                if (price.sale_color) css += cardSelector + ' .impulse-pcard-price .sale-price { color: ' + price.sale_color + ' !important; }';

                var btn = cardDesign.add_to_cart || {};
                var btnFontSize = (device !== 'desktop' && btn['font_size_' + device] !== undefined) ? btn['font_size_' + device] : btn.font_size;
                var btnRadius = (device !== 'desktop' && btn['border_radius_' + device] !== undefined) ? btn['border_radius_' + device] : btn.border_radius;
                if (btn.bg_color) css += cardSelector + ' .impulse-pcard-btn { background: ' + btn.bg_color + ' !important; }';
                if (btn.text_color) css += cardSelector + ' .impulse-pcard-btn { color: ' + btn.text_color + ' !important; }';
                if (btnRadius !== undefined) css += cardSelector + ' .impulse-pcard-btn { border-radius: ' + btnRadius + 'px !important; }';
                if (btnFontSize) css += cardSelector + ' .impulse-pcard-btn { font-size: ' + btnFontSize + 'px !important; }';
                
                if (btn.bg_color) css += '.impulse-quickview-add-btn { background: ' + btn.bg_color + ' !important; }';
                if (btn.text_color) css += '.impulse-quickview-add-btn { color: ' + btn.text_color + ' !important; }';
                if (btnRadius !== undefined) css += '.impulse-quickview-add-btn { border-radius: ' + btnRadius + 'px !important; }';

                var badge = cardDesign.sale_badge || {};
                var badgeBgInp = document.querySelector('input[name="card_design_sale_badge_bg_color"]');
                var badgeFeaturedBgInp = document.querySelector('input[name="card_design_featured_badge_bg_color"]');
                var badgeTxtInp = document.querySelector('input[name="card_design_sale_badge_text_color"]');
                var badgeBg = (badgeBgInp && badgeBgInp.value) || badge.bg_color;
                var badgeFeaturedBg = (badgeFeaturedBgInp && badgeFeaturedBgInp.value) || badge.featured_bg_color || badge.bg_color;
                var badgeTxt = (badgeTxtInp && badgeTxtInp.value) || badge.text_color;
                
                if (badgeBg) css += cardSelector + '{--badge-bg:' + badgeBg + '!important}';
                if (badgeFeaturedBg) css += cardSelector + '{--featured-badge-bg:' + badgeFeaturedBg + '!important}';
                if (badgeTxt) css += cardSelector + '{--badge-txt:' + badgeTxt + '!important}';

                var elemDevice = window.impulseDevice || 'desktop';
                var elemKey = elemDevice === 'desktop' ? 'elements' : 'elements_' + elemDevice;
                var elements = cardDesign[elemKey] !== undefined ? cardDesign[elemKey] : 
                               (cardDesign.elements || ['image','title','price','add_to_cart','sale_badge','featured_badge']);
                var elMap = {
                    image: '.impulse-pcard-image',
                    title: '.impulse-pcard-title',
                    price: '.impulse-pcard-price',
                    add_to_cart: '.impulse-pcard-btn-wrap',
                    description: '.impulse-pcard-desc'

                };
                Object.keys(elMap).forEach(function(k) {
                    if (!elements.includes(k)) {
                        css += cardSelector + ' ' + elMap[k] + ' { display: none !important; }';
                    }
                });

                if (renderType === 'products') {
                    var device = window.impulseDevice || 'desktop';
                    var colKey = device === 'desktop' ? 'columns' : 'columns_' + device;
                    var columns = parseInt(settings[colKey] !== undefined ? settings[colKey] : settings.columns) || 4;
                    var gridGap = parseInt(device === 'desktop' ? (settings.gap || 10) : (settings['gap_' + device] || 5));
                    var cardW = 'calc((100% - ' + ((columns - 1) * gridGap) + 'px) / ' + columns + ')';
                    css += elSelector + ' .impulse-product-grid > * { flex: 0 0 ' + cardW + '; max-width: min(' + cardW + ', 380px); }';
                }
                
                if (css) {
                    var styleId = 'impulse-live-' + id;
                    var doc = iframe.contentDocument;
                    var existingStyle = doc.getElementById(styleId);
                    if (existingStyle) {
                        existingStyle.textContent = css;
                    } else {
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }

                var prevSettings = window.productGridPrevSettings || {};
                var structuralKeys = ['display_mode','source','query_type','product_ids','category_id',
                    'count','columns','carousel_cards','columns_tablet','columns_mobile','gap','gap_tablet','gap_mobile',
                    'carousel_mode','single_effect','scroll_speed','show_nav','flip_cards','flip_card_effect',
                    'section_max_width','section_padding_v','section_padding_h',
                    
                    'pl_separator','pl_show_divider','pl_title_color','pl_price_color','pl_desc_color','pl_sep_color',
                    'pl_border_color','pl_title_size','pl_price_size','pl_desc_size','pl_spacing',
                    'menu_show_desc','menu_show_thumb','menu_show_button','menu_btn_label','menu_btn_bg','menu_btn_color','menu_btn_radius','menu_thumb_size'];
                var needsRefresh = structuralKeys.some(function(k) { return prevSettings[k] !== settings[k]; });

                if (!needsRefresh && dm === 'carousel' && settings.carousel_mode !== 'scroll') needsRefresh = needsRefresh || prevSettings.columns !== settings.columns;
                
                if (!needsRefresh && settings.card_design) {
                    
                    function cardDesignStructural(cd) {
                        if (!cd) return {};
                        return {
                            elements: cd.elements,
                            sale_badge: cd.sale_badge ? { text: (cd.sale_badge.text||''), featured_text: (cd.sale_badge.featured_text||'') } : {},
                            add_to_cart: { button_text: (cd.add_to_cart||{}).button_text || '' }
                        };
                    }
                    var cdChanged = JSON.stringify(cardDesignStructural(settings.card_design)) !== JSON.stringify(cardDesignStructural(prevSettings.card_design));
                    if (cdChanged) needsRefresh = true;
                }
                    
                window.productGridPrevSettings = JSON.parse(JSON.stringify(settings));
                return needsRefresh ? 'needs-refresh' : 'ok';
            }

            if (type === 'carousel') {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return 'needs-refresh';
                var doc = iframe.contentDocument;
                var elSelector = '.impulse-el[data-id="' + id + '"]';
                var carSelector = elSelector + ' .impulse-image-carousel';
                var trackSelector = elSelector + ' .impulse-carousel-track';
                var css = '';
                if (settings.height !== undefined) {
                    css += trackSelector + ' { height: ' + parseInt(settings.height) + 'px !important; }';
                }
                if (settings.slider_width !== undefined) {
                    var sw = parseInt(settings.slider_width) || 0;
                    if (sw > 0 && sw < 100) {
                        css += carSelector + ' { width: ' + sw + '% !important; }';
                    } else {
                        css += carSelector + ' { width: 100% !important; }';
                    }
                }
                if (css) {
                    var styleId = 'impulse-live-' + id;
                    var existingStyle = doc.getElementById(styleId);
                    if (existingStyle) { existingStyle.textContent = css; }
                    else { var s = doc.createElement('style'); s.id = styleId; s.textContent = css; if (doc.head) doc.head.appendChild(s); }
                }
                
                var elWrapSelector = '.impulse-el[data-id="' + id + '"]';
                if (settings.border_radius !== undefined) css += carSelector + ' { border-radius: ' + parseInt(settings.border_radius) + 'px !important; }';
                if (settings.bg_color) css += carSelector + ' { background: ' + settings.bg_color + ' !important; }';
                if (settings.margin_top !== undefined) css += elWrapSelector + ' { margin-top: ' + parseInt(settings.margin_top) + 'px !important; }';
                if (settings.margin_bottom !== undefined) css += elWrapSelector + ' { margin-bottom: ' + parseInt(settings.margin_bottom) + 'px !important; }';
                if (css) {
                    var styleId = 'impulse-live-' + id;
                    var existingStyle = doc.getElementById(styleId);
                    if (existingStyle) { existingStyle.textContent = css; }
                    else { var s = doc.createElement('style'); s.id = styleId; s.textContent = css; if (doc.head) doc.head.appendChild(s); }
                }
                
                var imgCar = doc.querySelector(elWrapSelector + ' .impulse-image-carousel');
                if (imgCar && settings.scroll_speed !== undefined) {
                    var newSpeed = parseInt(settings.scroll_speed) || 3;
                    imgCar.dataset.speed = Math.round(60 / Math.max(1, newSpeed));
                }
                
                if (imgCar && settings.autoplay_speed !== undefined) {
                    imgCar.dataset.interval = (parseInt(settings.autoplay_speed) || 4) * 1000;
                }
                
                var prevSettings = window.newSliderPrevSettings || {};
                var needsRefresh = false;
                var structuralKeys = ['animation_mode','slider_effect','content_type','direction','items_to_show','gap','autoplay','pause_hover','object_fit','images','slides'];
                for (var _ki = 0; _ki < structuralKeys.length; _ki++) {
                    if (JSON.stringify(prevSettings[structuralKeys[_ki]]) !== JSON.stringify(settings[structuralKeys[_ki]])) { needsRefresh = true; break; }
                }
                window.newSliderPrevSettings = JSON.parse(JSON.stringify(settings));
                return needsRefresh ? 'needs-refresh' : 'ok';
            }

            if (type === 'slider') {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return 'needs-refresh';
                
                var doc = iframe.contentDocument;
                var css = '';
                var elSelector = '.impulse-el[data-id="' + id + '"]';
                var sliderSelector = elSelector + ' .impulse-new-slider';
                var trackSelector = elSelector + ' .impulse-carousel-track';

                var hMode = settings.height_mode || 'fixed';
                if (settings.height !== undefined) {
                    if (hMode === 'auto') {
                        css += trackSelector + ' { height: auto !important; min-height: ' + settings.height + 'px !important; }';
                        css += elSelector + ' .impulse-carousel-slide { height: auto !important; min-height: ' + settings.height + 'px !important; }';
                        css += elSelector + ' .impulse-new-slider-dropzone { height: auto !important; min-height: ' + settings.height + 'px !important; }';
                    } else {
                        css += trackSelector + ' { height: ' + settings.height + 'px !important; }';
                        css += elSelector + ' .impulse-carousel-slide { height: ' + settings.height + 'px !important; }';
                        css += elSelector + ' .impulse-new-slider-dropzone { height: 100% !important; }';
                    }
                }
                
                var sliderEl = doc.querySelector(elSelector + ' .impulse-new-slider');
                if (sliderEl && sliderEl.dataset.heightMode !== hMode) {
                    sliderEl.dataset.heightMode = hMode;
                }
                
                if (settings.slider_width !== undefined) {
                    var sw = parseInt(settings.slider_width) || 1200;
                    css += sliderSelector + ' { max-width: ' + sw + 'px !important; margin-left: auto !important; margin-right: auto !important; }';
                }
                
                if (settings.transition_speed !== undefined) {
                    css += elSelector + ' .impulse-carousel-slides { transition-duration: ' + settings.transition_speed + 'ms !important; }';
                }
                
                if (settings.border_radius !== undefined) {
                    css += elSelector + ' { border-radius: ' + parseInt(settings.border_radius) + 'px !important; overflow: hidden; }';
                }
                
                if (settings.margin_top !== undefined) css += elSelector + ' { margin-top: ' + parseInt(settings.margin_top) + 'px !important; }';
                if (settings.margin_bottom !== undefined) css += elSelector + ' { margin-bottom: ' + parseInt(settings.margin_bottom) + 'px !important; }';

                var slides = settings.slides || [];
                if (typeof slides === 'string') {
                    try { slides = JSON.parse(slides); } catch(e) { slides = []; }
                }
                slides.forEach(function(slide, idx) {
                    if (slide && slide.background) {
                        css += elSelector + ' .impulse-carousel-slide[data-index="' + idx + '"] { background: ' + slide.background + ' !important; }';
                    }
                });
                
                if (css) {
                    var styleId = 'impulse-live-' + id;
                    var existingStyle = doc.getElementById(styleId);
                    if (existingStyle) {
                        existingStyle.textContent = css;
                    } else {
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }

                var currentSlide = parseInt(settings.current_slide) || 0;
                var sliderEl = doc.querySelector(elSelector + ' .impulse-new-slider');
                if (sliderEl && sliderEl._goToSlide) {
                    
                    sliderEl._goToSlide(currentSlide);
                    sliderEl.dataset.currentSlide = currentSlide;
                } else {
                    var slidesContainer = doc.querySelector(elSelector + ' .impulse-carousel-slides');
                    if (slidesContainer) {
                        slidesContainer.style.transform = 'translateX(-' + (currentSlide * 100) + '%)';
                    }
                }

                var prevBtn = doc.querySelector(elSelector + ' .impulse-carousel-prev');
                var nextBtn = doc.querySelector(elSelector + ' .impulse-carousel-next');
                var direction = settings.direction || 'both';
                if (prevBtn) prevBtn.style.display = (direction === 'both' || direction === 'prev') ? '' : 'none';
                if (nextBtn) nextBtn.style.display = (direction === 'both' || direction === 'next') ? '' : 'none';

                
                if (window['sliderInterval_' + id]) {
                    clearInterval(window['sliderInterval_' + id]);
                    window['sliderInterval_' + id] = null;
                }

                if (slides && slides.length) {
                    slides.forEach(function(slide, idx) {
                        var valign = slide.valign || 'center';
                        var jc = valign === 'top' ? 'flex-start' : valign === 'bottom' ? 'flex-end' : 'center';
                        var dz = doc.querySelector(elSelector + ' .impulse-carousel-slide[data-index="' + idx + '"] .impulse-new-slider-dropzone');
                        if (dz) dz.style.justifyContent = jc;
                    });
                }

                var prevSettings = window.newSliderPrevSettings || {};
                var slidesChanged = false;
                var prevSlides = prevSettings.slides || [];
                var currSlides = slides;
                if (prevSlides.length !== currSlides.length) { slidesChanged = true; }
                if ((prevSettings.height_mode || 'fixed') !== (settings.height_mode || 'fixed')) { slidesChanged = true; }
                if ((prevSettings.slider_effect || 'slide') !== (settings.slider_effect || 'slide')) { slidesChanged = true; }
                if ((prevSettings.content_type || 'images') !== (settings.content_type || 'images')) { slidesChanged = true; }
                if ((prevSettings.direction || 'right') !== (settings.direction || 'right')) { slidesChanged = true; }
                if ((parseInt(prevSettings.items_to_show) || 1) !== (parseInt(settings.items_to_show) || 1)) { slidesChanged = true; }
                if ((parseInt(prevSettings.gap) || 0) !== (parseInt(settings.gap) || 0)) { slidesChanged = true; }
                
                if (slidesChanged) {
                    window.newSliderPrevSettings = JSON.parse(JSON.stringify(settings));
                    return 'needs-refresh';
                }
                window.newSliderPrevSettings = JSON.parse(JSON.stringify(settings));
                return true;
            }

            
            if (type === 'rows') {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return 'needs-refresh';

                
                if (resolvedSettings.depth_intensity !== undefined) {
                    var _dEl = iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"] .impulse-rows');
                    if (_dEl) {
                        var _di = parseInt(resolvedSettings.depth_intensity) || 0;
                        if (_di > 0) _dEl.setAttribute('data-depth-intensity', _di);
                        else _dEl.removeAttribute('data-depth-intensity');
                    }
                }

                var css = '';
                var elSelector = '.impulse-el[data-id="' + id + '"]';
                var containerSelector = elSelector + ' .impulse-rows';
                var rowSelector = elSelector + ' .impulse-rows-row';
                var cellSelector = elSelector + ' .impulse-rows-cell';

                var rowGap = resolvedSettings.row_gap !== undefined ? resolvedSettings.row_gap : 16;
                var cellGap = resolvedSettings.cell_gap !== undefined ? resolvedSettings.cell_gap : 16;
                var rowHeight = resolvedSettings.row_height !== undefined ? resolvedSettings.row_height : 120;
                var cellRadius = resolvedSettings.cell_radius !== undefined ? resolvedSettings.cell_radius : 0;
                var paddingSides = resolvedSettings.padding_sides !== undefined ? resolvedSettings.padding_sides : 0;
                var paddingTop = resolvedSettings.padding_top !== undefined ? resolvedSettings.padding_top : 0;
                var paddingBottom = resolvedSettings.padding_bottom !== undefined ? resolvedSettings.padding_bottom : 0;
                var containerRadius = resolvedSettings.border_radius !== undefined ? resolvedSettings.border_radius : 0;
                var bgColor = resolvedSettings.bg_color || 'transparent';

                var containerBorderWidth = resolvedSettings.container_border_width || 0;
                var containerBorderColor = resolvedSettings.container_border_color || ''+ImpC.text+'';
                var containerBorderTop = resolvedSettings.container_border_top !== '0' && resolvedSettings.container_border_top !== 0;
                var containerBorderRight = resolvedSettings.container_border_right !== '0' && resolvedSettings.container_border_right !== 0;
                var containerBorderBottom = resolvedSettings.container_border_bottom !== '0' && resolvedSettings.container_border_bottom !== 0;
                var containerBorderLeft = resolvedSettings.container_border_left !== '0' && resolvedSettings.container_border_left !== 0;

                var globalCellBorderWidth = resolvedSettings.cell_border_width || 0;
                var globalCellBorderColor = resolvedSettings.cell_border_color || ''+ImpC.text+'';
                var globalCellBorderTop = resolvedSettings.cell_border_top !== '0' && resolvedSettings.cell_border_top !== 0;
                var globalCellBorderRight = resolvedSettings.cell_border_right !== '0' && resolvedSettings.cell_border_right !== 0;
                var globalCellBorderBottom = resolvedSettings.cell_border_bottom !== '0' && resolvedSettings.cell_border_bottom !== 0;
                var globalCellBorderLeft = resolvedSettings.cell_border_left !== '0' && resolvedSettings.cell_border_left !== 0;

                css += containerSelector + ' { gap: ' + rowGap + 'px !important; ';
                var minHeight = resolvedSettings.min_height !== undefined ? parseInt(resolvedSettings.min_height) : 0;
                if (minHeight > 0) css += 'min-height: ' + minHeight + 'px !important; ';
                var marginTop = resolvedSettings.margin_top !== undefined ? parseInt(resolvedSettings.margin_top) : 0;
                var marginBottom = resolvedSettings.margin_bottom !== undefined ? parseInt(resolvedSettings.margin_bottom) : 0;
                if (marginTop > 0) css += 'margin-top: ' + marginTop + 'px !important; ';
                if (marginBottom > 0) css += 'margin-bottom: ' + marginBottom + 'px !important; ';
                if (paddingTop > 0 || paddingSides > 0 || paddingBottom > 0) {
                    css += 'padding: ' + paddingTop + 'px ' + paddingSides + 'px ' + paddingBottom + 'px ' + paddingSides + 'px !important; ';
                }
                if (containerRadius > 0) css += 'border-radius: ' + containerRadius + 'px !important; overflow: hidden !important; ';
                if (bgColor && bgColor !== 'transparent') css += 'background-color: ' + bgColor + ' !important; ';
                
                if (containerBorderWidth > 0) {
                    var cbt = containerBorderTop ? containerBorderWidth + 'px' : '0';
                    var cbr = containerBorderRight ? containerBorderWidth + 'px' : '0';
                    var cbb = containerBorderBottom ? containerBorderWidth + 'px' : '0';
                    var cbl = containerBorderLeft ? containerBorderWidth + 'px' : '0';
                    css += 'border-width: ' + cbt + ' ' + cbr + ' ' + cbb + ' ' + cbl + ' !important; ';
                    css += 'border-style: solid !important; ';
                    css += 'border-color: ' + containerBorderColor + ' !important; ';
                }
                var maxWidth = resolvedSettings.max_width !== undefined ? parseInt(resolvedSettings.max_width) : 0;
                if (maxWidth > 0) css += 'max-width: ' + maxWidth + 'px !important; margin-left: auto !important; margin-right: auto !important; ';
                css += '}';

                var rows = resolvedSettings.rows;
                if (typeof rows === 'string') {
                    try { rows = JSON.parse(rows); } catch(e) { rows = []; }
                }
                var defaultRowHeight = 120; 
                
                if (rows && rows.length) {
                    rows.forEach(function(row, rowIdx) {
                        var thisRowHeight = row.row_height !== undefined ? row.row_height : defaultRowHeight;
                        var specificRowSelector = elSelector + ' .impulse-rows-row[data-row="' + rowIdx + '"]';
                        css += specificRowSelector + ' { gap: ' + cellGap + 'px !important; min-height: ' + thisRowHeight + 'px !important; }';
                        
                        var rowCellSelector = elSelector + ' .impulse-rows-cell[data-row="' + rowIdx + '"]';
                        css += rowCellSelector + ' { min-height: ' + thisRowHeight + 'px !important; }';
                    });
                } else {
                    
                    css += rowSelector + ' { gap: ' + cellGap + 'px !important; min-height: ' + defaultRowHeight + 'px !important; }';
                }

                css += cellSelector + ' { ';
                if (cellRadius > 0) css += 'border-radius: ' + cellRadius + 'px !important; overflow: hidden !important; ';
                
                if (globalCellBorderWidth > 0) {
                    var gcbt = globalCellBorderTop ? globalCellBorderWidth + 'px' : '0';
                    var gcbr = globalCellBorderRight ? globalCellBorderWidth + 'px' : '0';
                    var gcbb = globalCellBorderBottom ? globalCellBorderWidth + 'px' : '0';
                    var gcbl = globalCellBorderLeft ? globalCellBorderWidth + 'px' : '0';
                    css += 'border-width: ' + gcbt + ' ' + gcbr + ' ' + gcbb + ' ' + gcbl + ' !important; ';
                    css += 'border-style: solid !important; ';
                    css += 'border-color: ' + globalCellBorderColor + ' !important; ';
                }
                css += '}';

                if (rows && rows.length) {
                    rows.forEach(function(row, rowIdx) {
                        if (row.cells) {
                            var widths = row.widths || [];
                            row.cells.forEach(function(cell, colIdx) {
                                var specificCellSelector = elSelector + ' .impulse-rows-cell[data-row="' + rowIdx + '"][data-col="' + colIdx + '"]';
                                var cellContentSelector = specificCellSelector + ' .impulse-cell-content';
                                var cellCss = '';

                                if (widths[colIdx] !== undefined) {
                                    cellCss += 'flex: ' + widths[colIdx] + ' 1 0% !important; ';
                                }

                                if (cell.bg_color && cell.bg_color !== 'transparent') {
                                    cellCss += 'background-color: ' + cell.bg_color + ' !important; ';
                                }
                                if (cell.bg_image) {
                                    var bgFit = cell.bg_fit || 'cover';
                                    var bgPosition = cell.bg_position || 'center';
                                    cellCss += 'background-image: url(' + cell.bg_image + ') !important; ';
                                    cellCss += 'background-size: ' + bgFit + ' !important; ';
                                    cellCss += 'background-position: ' + bgPosition + ' !important; ';
                                    cellCss += 'background-repeat: no-repeat !important; ';
                                }

                                var pt = getCellDeviceVal(cell, 'padding_top', 0);
                                var ps = getCellDeviceVal(cell, 'padding_sides', cell.padding_left || 0);
                                var pb = getCellDeviceVal(cell, 'padding_bottom', 0);
                                if (pt || ps || pb) {
                                    cellCss += 'padding: ' + pt + 'px ' + ps + 'px ' + pb + 'px ' + ps + 'px !important; ';
                                }

                                if (cell.border_width && cell.border_width > 0) {
                                    var borderColor = cell.border_color || ''+ImpC.text+'';
                                    var bw = cell.border_width;
                                    var bt = cell.border_top !== '0' && cell.border_top !== 0 && cell.border_top !== false ? bw + 'px' : '0';
                                    var br = cell.border_right !== '0' && cell.border_right !== 0 && cell.border_right !== false ? bw + 'px' : '0';
                                    var bb = cell.border_bottom !== '0' && cell.border_bottom !== 0 && cell.border_bottom !== false ? bw + 'px' : '0';
                                    var bl = cell.border_left !== '0' && cell.border_left !== 0 && cell.border_left !== false ? bw + 'px' : '0';
                                    cellCss += 'border-width: ' + bt + ' ' + br + ' ' + bb + ' ' + bl + ' !important; ';
                                    cellCss += 'border-style: solid !important; ';
                                    cellCss += 'border-color: ' + borderColor + ' !important; ';
                                }
                                
                                if (cellCss) {
                                    css += specificCellSelector + ' { ' + cellCss + '}';
                                }

                                

                                

                                

                                var valign = getCellDeviceVal(cell, 'valign', 'top');
                                var halign = getCellDeviceVal(cell, 'halign', 'center');
                                var justify = valign === 'top' ? 'flex-start' : (valign === 'bottom' ? 'flex-end' : 'center');
                                var alignI  = halign === 'left' ? 'flex-start' : (halign === 'right'  ? 'flex-end' : 'center');
                                css += cellContentSelector + ' { justify-content: ' + justify + ' !important; align-items: ' + alignI + ' !important; }';

                                var overlaySelector = specificCellSelector + ' .impulse-cell-overlay';
                                if (cell.overlay_color) {
                                    css += overlaySelector + ' { background-color: ' + cell.overlay_color + ' !important; }';
                                }
                            });
                        }
                    });
                }
                
                if (css) {
                    var styleId = 'impulse-live-' + id;
                    var doc = iframe.contentDocument;
                    var existingStyle = doc.getElementById(styleId);
                    if (existingStyle) {
                        existingStyle.textContent = css;
                    } else {
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }

                
                (function() {
                    var _mw = parseInt(resolvedSettings.max_width) || 0;
                    var _mwCss = _mw > 0 ? 'max-width:' + _mw + 'px;' : '';
                    var _ifrDoc = window.impulseCSSVars && window.impulseCSSVars.getDoc ? window.impulseCSSVars.getDoc() : null;
                    if (_ifrDoc) {
                        var _sid = 'impulse-live-mw-' + id;
                        var _sel = '.impulse-el[data-id="' + id + '"]';
                        var _mwEl = _ifrDoc.getElementById(_sid);
                        var _mwRule = _sel + ' .impulse-grid-wrapper,' + _sel + ' .impulse-grid,' + _sel + ' .impulse-rows-container,' + _sel + ' .impulse-layout-grid{' + _mwCss + 'margin-left:auto!important;margin-right:auto!important}';
                        if (_mwEl) { _mwEl.textContent = _mwRule; }
                        else { var _st = _ifrDoc.createElement('style'); _st.id = _sid; _st.textContent = _mwRule; _ifrDoc.head.appendChild(_st); }
                    }
                })();
                return 'ok';
            }

            if (type === 'columns') {
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return 'needs-refresh';

                if (resolvedSettings.depth_intensity !== undefined) {
                    var _dEl = iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"] .impulse-layout-grid');
                    if (_dEl) {
                        var _di = parseInt(resolvedSettings.depth_intensity) || 0;
                        if (_di > 0) _dEl.setAttribute('data-depth-intensity', _di);
                        else _dEl.removeAttribute('data-depth-intensity');
                    }
                }

                var css = '';
                var elSelector = '.impulse-el[data-id="' + id + '"]';
                var containerSelector = elSelector + ' .impulse-layout-grid';
                var colSelector = elSelector + ' .impulse-layout-col';
                var cellSelector = elSelector + ' .impulse-layout-cell';

                var colGap = resolvedSettings.col_gap !== undefined ? resolvedSettings.col_gap : 16;
                var cellGap = resolvedSettings.cell_gap !== undefined ? resolvedSettings.cell_gap : 16;
                var minHeight = resolvedSettings.min_height !== undefined ? resolvedSettings.min_height : 200;
                var cellRadius = resolvedSettings.cell_radius !== undefined ? resolvedSettings.cell_radius : 0;
                var paddingSides = resolvedSettings.padding_sides !== undefined ? resolvedSettings.padding_sides : 0;
                var paddingTop = resolvedSettings.padding_top !== undefined ? resolvedSettings.padding_top : 0;
                var paddingBottom = resolvedSettings.padding_bottom !== undefined ? resolvedSettings.padding_bottom : 0;
                var containerRadius = resolvedSettings.border_radius !== undefined ? resolvedSettings.border_radius : 0;
                var bgColor = resolvedSettings.bg_color || 'transparent';

                var containerBorderWidth = resolvedSettings.container_border_width || 0;
                var containerBorderColor = resolvedSettings.container_border_color || ''+ImpC.text+'';
                var containerBorderTop = resolvedSettings.container_border_top !== '0' && resolvedSettings.container_border_top !== 0;
                var containerBorderRight = resolvedSettings.container_border_right !== '0' && resolvedSettings.container_border_right !== 0;
                var containerBorderBottom = resolvedSettings.container_border_bottom !== '0' && resolvedSettings.container_border_bottom !== 0;
                var containerBorderLeft = resolvedSettings.container_border_left !== '0' && resolvedSettings.container_border_left !== 0;

                var globalCellBorderWidth = resolvedSettings.cell_border_width || 0;
                var globalCellBorderColor = resolvedSettings.cell_border_color || ''+ImpC.text+'';
                var globalCellBorderTop = resolvedSettings.cell_border_top !== '0' && resolvedSettings.cell_border_top !== 0;
                var globalCellBorderRight = resolvedSettings.cell_border_right !== '0' && resolvedSettings.cell_border_right !== 0;
                var globalCellBorderBottom = resolvedSettings.cell_border_bottom !== '0' && resolvedSettings.cell_border_bottom !== 0;
                var globalCellBorderLeft = resolvedSettings.cell_border_left !== '0' && resolvedSettings.cell_border_left !== 0;

                var columns = resolvedSettings.columns;
                if (typeof columns === 'string') {
                    try { columns = JSON.parse(columns); } catch(e) { columns = []; }
                }

                var colTemplate = '';
                if (columns && columns.length) {
                    colTemplate = columns.map(function(col) {
                        return (col.width || (100 / columns.length)).toFixed(2) + 'fr';
                    }).join(' ');
                }

                css += containerSelector + ' { ';
                if (colTemplate) css += 'grid-template-columns: ' + colTemplate + ' !important; ';
                css += 'gap: ' + colGap + 'px !important; ';
                if (minHeight > 0) css += 'min-height: ' + minHeight + 'px !important; ';
                var marginTop = resolvedSettings.margin_top !== undefined ? parseInt(resolvedSettings.margin_top) : 0;
                var marginBottom = resolvedSettings.margin_bottom !== undefined ? parseInt(resolvedSettings.margin_bottom) : 0;
                if (marginTop > 0) css += 'margin-top: ' + marginTop + 'px !important; ';
                if (marginBottom > 0) css += 'margin-bottom: ' + marginBottom + 'px !important; ';
                if (paddingTop > 0 || paddingSides > 0 || paddingBottom > 0) {
                    css += 'padding: ' + paddingTop + 'px ' + paddingSides + 'px ' + paddingBottom + 'px ' + paddingSides + 'px !important; ';
                }
                if (containerRadius > 0) css += 'border-radius: ' + containerRadius + 'px !important; overflow: hidden !important; ';
                if (bgColor && bgColor !== 'transparent') css += 'background-color: ' + bgColor + ' !important; ';
                if (containerBorderWidth > 0) {
                    var cbt = containerBorderTop ? containerBorderWidth + 'px' : '0';
                    var cbr = containerBorderRight ? containerBorderWidth + 'px' : '0';
                    var cbb = containerBorderBottom ? containerBorderWidth + 'px' : '0';
                    var cbl = containerBorderLeft ? containerBorderWidth + 'px' : '0';
                    css += 'border-width: ' + cbt + ' ' + cbr + ' ' + cbb + ' ' + cbl + ' !important; ';
                    css += 'border-style: solid !important; ';
                    css += 'border-color: ' + containerBorderColor + ' !important; ';
                }
                var maxWidth = resolvedSettings.max_width !== undefined ? parseInt(resolvedSettings.max_width) : 0;
                if (maxWidth > 0) css += 'max-width: ' + maxWidth + 'px !important; margin-left: auto !important; margin-right: auto !important; ';
                css += '}';

                css += colSelector + ' { gap: ' + cellGap + 'px !important; }';

                css += cellSelector + ' { ';
                css += 'border-radius: ' + cellRadius + 'px !important; ';
                if (cellRadius > 0) css += 'overflow: hidden !important; ';
                else css += 'overflow: visible !important; ';
                if (globalCellBorderWidth > 0) {
                    var gcbt = globalCellBorderTop ? globalCellBorderWidth + 'px' : '0';
                    var gcbr = globalCellBorderRight ? globalCellBorderWidth + 'px' : '0';
                    var gcbb = globalCellBorderBottom ? globalCellBorderWidth + 'px' : '0';
                    var gcbl = globalCellBorderLeft ? globalCellBorderWidth + 'px' : '0';
                    css += 'border-width: ' + gcbt + ' ' + gcbr + ' ' + gcbb + ' ' + gcbl + ' !important; ';
                    css += 'border-style: solid !important; ';
                    css += 'border-color: ' + globalCellBorderColor + ' !important; ';
                }
                css += '}';

                css += cellSelector + ' .impulse-cell-empty-indicator { border-radius: ' + cellRadius + 'px !important; }';

                if (columns && columns.length) {
                    columns.forEach(function(col, colIdx) {
                        if (col.cells) {
                            col.cells.forEach(function(cell, rowIdx) {
                                var specificCellSelector = elSelector + ' .impulse-layout-cell[data-col="' + colIdx + '"][data-row="' + rowIdx + '"]';
                                var cellContentSelector = specificCellSelector + ' .impulse-cell-content';
                                var cellCss = '';
                                
                                if (cell.bg_color && cell.bg_color !== 'transparent') {
                                    cellCss += 'background-color: ' + cell.bg_color + ' !important; ';
                                }
                                if (cell.bg_image) {
                                    var bgFit = cell.bg_fit || 'cover';
                                    var bgPosition = cell.bg_position || 'center';
                                    cellCss += 'background-image: url(' + cell.bg_image + ') !important; ';
                                    cellCss += 'background-size: ' + bgFit + ' !important; ';
                                    cellCss += 'background-position: ' + bgPosition + ' !important; ';
                                    cellCss += 'background-repeat: no-repeat !important; ';
                                }
                                
                                var pt = getCellDeviceVal(cell, 'padding_top', 0);
                                var ps = getCellDeviceVal(cell, 'padding_sides', 0);
                                var pb = getCellDeviceVal(cell, 'padding_bottom', 0);
                                if (pt || ps || pb) {
                                    cellCss += 'padding: ' + pt + 'px ' + ps + 'px ' + pb + 'px ' + ps + 'px !important; ';
                                }
                                
                                if (cell.border_width && cell.border_width > 0) {
                                    var borderColor = cell.border_color || ''+ImpC.text+'';
                                    var bw = cell.border_width;
                                    var bt = cell.border_top !== '0' && cell.border_top !== 0 && cell.border_top !== false ? bw + 'px' : '0';
                                    var br = cell.border_right !== '0' && cell.border_right !== 0 && cell.border_right !== false ? bw + 'px' : '0';
                                    var bb = cell.border_bottom !== '0' && cell.border_bottom !== 0 && cell.border_bottom !== false ? bw + 'px' : '0';
                                    var bl = cell.border_left !== '0' && cell.border_left !== 0 && cell.border_left !== false ? bw + 'px' : '0';
                                    cellCss += 'border-width: ' + bt + ' ' + br + ' ' + bb + ' ' + bl + ' !important; ';
                                    cellCss += 'border-style: solid !important; ';
                                    cellCss += 'border-color: ' + borderColor + ' !important; ';
                                }

                                if (cell.hide_desktop === '1' || cell.hide_desktop === 1) {
                                    css += specificCellSelector + '.impulse-hide-desktop { }';
                                }
                                if (cell.hide_tablet === '1' || cell.hide_tablet === 1) {
                                    css += specificCellSelector + '.impulse-hide-tablet { }';
                                }
                                if (cell.hide_mobile === '1' || cell.hide_mobile === 1) {
                                    css += specificCellSelector + '.impulse-hide-mobile { }';
                                }
                                
                                if (cellCss) {
                                    css += specificCellSelector + ' { ' + cellCss + '}';
                                }

                                var valign = getCellDeviceVal(cell, 'valign', 'top');
                                var justify = valign === 'top' ? 'flex-start' : (valign === 'bottom' ? 'flex-end' : 'center');
                                css += cellContentSelector + ' { justify-content: ' + justify + ' !important; }';
                            });
                        }
                    });
                }
                
                if (css) {
                    var styleId = 'impulse-live-' + id;
                    var doc = iframe.contentDocument;
                    var existingStyle = doc.getElementById(styleId);
                    if (existingStyle) {
                        existingStyle.textContent = css;
                    } else {
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                    }
                }

                
                (function() {
                    var _mw = parseInt(resolvedSettings.max_width) || 0;
                    var _mwCss = _mw > 0 ? 'max-width:' + _mw + 'px;' : '';
                    var _ifrDoc = window.impulseCSSVars && window.impulseCSSVars.getDoc ? window.impulseCSSVars.getDoc() : null;
                    if (_ifrDoc) {
                        var _sid = 'impulse-live-mw-' + id;
                        var _sel = '.impulse-el[data-id="' + id + '"]';
                        var _mwEl = _ifrDoc.getElementById(_sid);
                        var _mwRule = _sel + ' .impulse-grid-wrapper,' + _sel + ' .impulse-grid,' + _sel + ' .impulse-rows-container,' + _sel + ' .impulse-layout-grid{' + _mwCss + 'margin-left:auto!important;margin-right:auto!important}';
                        if (_mwEl) { _mwEl.textContent = _mwRule; }
                        else { var _st = _ifrDoc.createElement('style'); _st.id = _sid; _st.textContent = _mwRule; _ifrDoc.head.appendChild(_st); }
                    }
                })();
                return 'ok';
            }
            
            var previewSettings = $.extend({}, settings);
            if (device !== 'desktop') {
                
                var responsiveKeys = [
                    
                    'width', 'height', 'thickness', 'size', 'max_width', 'content_width', 'section_max_width', 'form_width',
                    
                    'margin_top', 'margin_bottom', 'margin_left', 'margin_right',
                    
                    'padding', 'padding_top', 'padding_bottom', 'padding_left', 'padding_right',
                    
                    'align', 'position_align', 'element_align',
                    
                    'line_height', 'letter_spacing', 'title_size', 'font_size', 'subtitle_size', 'content_size',
                    
                    'element_icon_size', 'icon_padding', 'icon_radius', 'icon_border_width',
                    'element_text_size', 'element_spacing', 'rounded',
                    
                    'icon_size', 'icon_spacing', 'button_size', 'button_padding',
                    
                    'space',
                    
                    'border_radius', 'border_width',
                    
                    'gap', 'row_gap', 'column_gap', 'columns',
                    
                    'bg_size',
                    
                    'number_size',
                    
                    'prefix_size', 'title_size',
                    
                    'label_size', 'box_padding', 'box_radius',
                    
                    'padding',
                    
                    'thumb_width',
                    
                    'height',
                    
                    'font_size'
                ];
                responsiveKeys.forEach(function(key) {
                    var deviceKey = key + '_' + device;
                    if (previewSettings[deviceKey] !== undefined) {
                        previewSettings[key] = previewSettings[deviceKey];
                    }
                });
            }

            
            
            var elConfig = window.ImpulseElementConfig ? window.ImpulseElementConfig.get(type) : null;
            if (window.impulseDebug) console.log('[livePreview] Generic injection:', type, 'config:', !!elConfig, 'settings:', Object.keys(resolvedSettings).length);
            if (elConfig && elConfig.settings) {
                var doc = window.impulseCSSVars.getDoc();
                if (doc) {
                    var wrapperSel = '.impulse-el[data-id="' + id + '"]';

                    
                    
                    var _portalSel = '.impulse-modal-scrim[data-modal-owner="' + id + '"]';
                    var css = '';
                    var unitMap = window.impulseCSSVars.units;
                    
                    for (var settingKey in elConfig.settings) {
                        var cfg = elConfig.settings[settingKey];
                        if (!cfg) continue;

                        var val = resolvedSettings[settingKey];
                        if (val === undefined || val === null || val === '') continue;

                        if (typeof cfg.custom === 'function') {
                            var customCss = cfg.custom(null, val, id);
                            if (customCss) css += customCss;
                            continue;
                        }

                        var hasRules = Array.isArray(cfg.rules) && cfg.rules.length;
                        if (!hasRules && (!cfg.selector || !cfg.property)) continue;

                        var cssVal;
                        if (cfg.transform && typeof cfg.transform === 'function') {
                            cssVal = cfg.transform(val);
                        } else if (cfg.unit && typeof cfg.unit === 'function') {
                            cssVal = cfg.unit(val);
                        } else if (unitMap[settingKey]) {
                            var u = unitMap[settingKey];
                            if (settingKey === 'line_height') {
                                cssVal = parseFloat(val) / 100;
                            } else if (u) {
                                cssVal = val + u;
                            } else {
                                cssVal = val;
                            }
                        } else {
                            cssVal = val;
                        }
                        if (cssVal === null || cssVal === undefined || cssVal === '') continue;

                        if (cssVal === '#000000' && settingKey === 'bg_color') continue;

                        var rulesList = hasRules ? cfg.rules : [{ selector: cfg.selector, property: cfg.property }];
                        for (var ri = 0; ri < rulesList.length; ri++) {
                            var rule = rulesList[ri];
                            if (!rule.selector || !rule.property) continue;
                            
                            var ruleVal = (rule.transform && typeof rule.transform === 'function') ? rule.transform(val) : cssVal;
                            if (ruleVal === null || ruleVal === undefined || ruleVal === '') continue;
                            var selectors = Array.isArray(rule.selector) ? rule.selector : [rule.selector];
                            var resolvedSels = [];
                            for (var si = 0; si < selectors.length; si++) {
                                resolvedSels.push(selectors[si].replace(/\{\{WRAPPER\}\}/g, wrapperSel).replace(/\{\{PORTAL\}\}/g, _portalSel));
                            }
                            var props = Array.isArray(rule.property) ? rule.property : [rule.property];
                            css += resolvedSels.join(',') + '{' + props.map(function(p){
                                var rv = ruleVal;
                                if (p === 'font-family' && rv && rv.indexOf("'") === -1 && rv.indexOf('"') === -1) {
                                    rv = "'" + rv + "',sans-serif";
                                }
                                return p + ':' + rv + '!important';
                            }).join(';') + '}';
                        }
                    }
                    
                    if (css) {
                        var styleId = 'impulse-live-cfg-' + id;
                        var existing = doc.getElementById(styleId);
                        if (existing) existing.remove();
                        var style = doc.createElement('style');
                        style.id = styleId;
                        style.textContent = css;
                        if (doc.head) doc.head.appendChild(style);
                        var elType = (window.impulseCSSVars && doc.querySelector('.impulse-el[data-id="'+id+'"]')) ? doc.querySelector('.impulse-el[data-id="'+id+'"]').dataset.type : '?';
                    } else if (window.impulseDebug) {
                    }
                }
            }

            
            if (!window._impulsePrevStructural) window._impulsePrevStructural = {};
            var structuralList = elConfig ? (elConfig.structural || []) : [];
            if (structuralList.length > 0) {
                var curStructObj = {};
                var strippedSettings = stripEntrance(settings);
                for (var sk = 0; sk < structuralList.length; sk++) {
                    curStructObj[structuralList[sk]] = strippedSettings[structuralList[sk]];
                }
                var curStructJson = JSON.stringify(curStructObj);
                var prevStructJson = window._impulsePrevStructural[id] || null;
                window._impulsePrevStructural[id] = curStructJson;

                if (!prevStructJson) {
                    var _existBase = $('.impulse-panel-right').data('existing-settings') || {};
                    var _prevObj = {};
                    for (var sk = 0; sk < structuralList.length; sk++) {
                        _prevObj[structuralList[sk]] = _existBase[structuralList[sk]];
                    }
                    prevStructJson = JSON.stringify(_prevObj);
                }
                
                if (prevStructJson && prevStructJson !== curStructJson) {
                    return 'needs-refresh';
                }
            } else if (!elConfig) {

                

            }

            
            
            if (type === 'grid' && resolvedSettings.depth_intensity !== undefined) {
                var _ifrG = document.getElementById('impulse-iframe');
                var _docG = _ifrG && _ifrG.contentDocument;
                if (_docG) {
                    var _gEl = _docG.querySelector('.impulse-el[data-id="' + id + '"] .impulse-grid');
                    if (_gEl) {
                        var _di = parseInt(resolvedSettings.depth_intensity) || 0;
                        if (_di > 0) {
                            _gEl.setAttribute('data-depth-intensity', _di);

                            if (!_gEl.hasAttribute('data-depth-cols')) {
                                var _c = parseInt(resolvedSettings.columns) || 2;
                                _gEl.setAttribute('data-depth-cols', _c);
                            }
                        } else {
                            _gEl.removeAttribute('data-depth-intensity');
                        }
                    }
                }
            }

            return 'ok';
        }

        
        
        var saveQueue = [];
        var saveInFlight = false;
        var saveInFlightId = null;

        
        function impulseAnimatorSvgAutoLoad() {
            var $pending = $('#impulse-la-svg-pending');
            if (!$pending.length) return;
            var svgUrl = $pending.data('url');
            if (!svgUrl) { $pending.text('No image URL'); return; }
            $.ajax({
                url:  ajaxurl,
                type: 'POST',
                data: { action: 'instinctor_svg_colors', nonce: Impulse.nonce, url: svgUrl },
                success: function(resp) {
                    if (!resp.success || !resp.data || !resp.data.length) {
                        $pending.text('No colors found');
                        return;
                    }
                    var found = {};
                    resp.data.forEach(function(c) { found[c] = c; });
                    var colorJson = JSON.stringify(found);
                    $('input[name="la_svg_colors"]').val(colorJson);
                    var _id = $('.impulse-panel-right').data('element-id');
                    var _ex = $('.impulse-panel-right').data('existing-settings') || {};
                    var _s  = collectSettingsFromPanel(_ex);
                    var _m  = $.extend({}, _ex, _s);
                    $('.impulse-panel-right').data('existing-settings', _m);
                    $('#impulse-settings-body').html(buildSettingsForm('title', _m, []));
                    enqueueSave(_id, _m, null);
                },
                error: function() { $pending.text('Could not load colors'); }
            });
        }

        function enqueueSave(id, mergedSettings, callback) {
            
            if (deletePending[id]) return;
            window._impulsePageEdited = true;   
            
            for (var i = 0; i < saveQueue.length; i++) {
                if (saveQueue[i].id === id) {
                    saveQueue[i].settings = mergedSettings;
                    saveQueue[i].callback = callback;
                    return;
                }
            }
            saveQueue.push({ id: id, settings: mergedSettings, callback: callback });
            processSaveQueue();

            

            

            
            
            if (window._impulseTimelineRecord && window.ImpulseTimelineEditor
                && typeof window.ImpulseTimelineEditor.addKeyframeForElement === 'function') {
                setTimeout(function() {
                    try { window.ImpulseTimelineEditor.addKeyframeForElement(id); } catch(e) {}
                }, 0);
            }
        }
        
        function processSaveQueue() {
            if (saveInFlight || saveQueue.length === 0) return;
            var item = saveQueue.shift();
            
            if (deletePending[item.id]) {
                processSaveQueue();
                return;
            }
            saveInFlight = true;
            saveInFlightId = item.id;

            

            

            var _putSettings = item.settings;
            if (_putSettings && Object.prototype.hasOwnProperty.call(_putSettings, 'keyframes')) {
                _putSettings = $.extend({}, _putSettings);
                delete _putSettings.keyframes;
            }
            $.ajax({
                url: Impulse.api + 'elements/' + item.id,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ settings: _putSettings, page_id: Impulse.pageId }),
                success: function() {
                    if (item.callback) item.callback(true);
                },
                error: function() {
                    if (item.callback) item.callback(false);
                },
                complete: function() {
                    saveInFlight = false;
                    saveInFlightId = null;
                    processSaveQueue();
                }
            });
        }

        var viewportPreserve = {
            _scrollTop: 0,
            _elementId: null,

            

            _getScroll: function(iframe) {
                try {
                    var win = iframe.contentWindow, doc = iframe.contentDocument;
                    return (doc && doc.body && doc.body.scrollTop) ||
                           (win && win.scrollY) ||
                           (doc && doc.documentElement && doc.documentElement.scrollTop) || 0;
                } catch(e) { return 0; }
            },
            _setScroll: function(iframe, y) {
                try {
                    var win = iframe.contentWindow, doc = iframe.contentDocument;
                    if (doc && doc.body) doc.body.scrollTop = y;                  
                    if (doc && doc.documentElement) doc.documentElement.scrollTop = y;
                    if (win) win.scrollTo(0, y);                                   
                } catch(e) {}
            },
            capture: function() {
                var iframe = document.getElementById('impulse-iframe');
                if (iframe) this._scrollTop = this._getScroll(iframe);
                
                this._elementId = selectedElementId || null;
            },
            restore: function() {
                var self = this;
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe) return;
                var win, doc;
                try { win = iframe.contentWindow; doc = iframe.contentDocument; } catch(e) { return; }

                

                if (self._elementId && win && doc) {
                    try {
                        var el = doc.querySelector('.impulse-el[data-id="' + self._elementId + '"]');
                        if (el) {
                            var iframeH = iframe.clientHeight || win.innerHeight || 600;
                            var cur     = self._getScroll(iframe);
                            var rect    = el.getBoundingClientRect();
                            var absTop  = rect.top + cur;
                            var absBot  = rect.bottom + cur;
                            var capY    = self._scrollTop || 0;
                            var wasVisible = absTop < capY + iframeH && absBot > capY;
                            if (!wasVisible) {
                                self._setScroll(iframe, Math.max(0, absTop + rect.height / 2 - iframeH / 2));
                                return;
                            }
                            
                        }
                    } catch(e) {}
                }
                
                self._setScroll(iframe, self._scrollTop || 0);
            }
        };

        var autoSaveTimer = null;
        window._autoSaveTimer = null; 
        function autoSaveAndPreview(immediate) {
            if (window._impulseRendering) return; 
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) {
                
                if (isPageSettingsMode()) {
                    autoSavePageSettings(false);
                }
                return;
            }
            if (deletePending[id]) return; 
            if (isDragActive) return; 
            if (isPageSettingsMode()) {
                autoSavePageSettings(false);
                return;
            }
            if ($('#impulse-settings-body').text().indexOf('Loading') !== -1) return;

            viewportPreserve.capture();

            var result = livePreviewSettings(immediate);

            if (result === 'needs-refresh') window._pendingRefreshId = id;
            var _needsRefresh = (window._pendingRefreshId === id);

            setTimeout(function() {
                viewportPreserve.restore();
            }, 20);

            clearTimeout(autoSaveTimer);
            var delay = immediate ? 0 : 300;
            showSaveStatus(true); 
            autoSaveTimer = setTimeout(function() {

                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var settings = collectSettingsFromPanel(existingSettings);
                var mergedSettings = $.extend({}, existingSettings, settings);

                var oldJson = JSON.stringify(existingSettings);
                var newJson = JSON.stringify(mergedSettings);
                if (oldJson !== newJson) {
                    saveToHistory('update', {
                        elementId: id,
                        oldSettings: JSON.parse(oldJson),
                        newSettings: JSON.parse(newJson)
                    });
                }
                
enqueueSave(id, mergedSettings, function(success) {
                    if (!success) return;
                    if (deletePending[id]) return;
                    
                    if ($('.impulse-panel-right').data('element-id') == id) {
                        $('.impulse-panel-right').data('existing-settings', mergedSettings);
                    }
                    showSaveStatus(); 

                    if (_needsRefresh) { window._pendingRefreshId = null; refreshElement(id); }
                });
            }, delay);
        }

        

        var autoRefreshTimer = null;
        function autoSaveAndRefresh() {
            
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) {
                if (isPageSettingsMode()) {
                    autoSavePageSettings(true);
                }
                return;
            }
            if (deletePending[id]) return;
            if (isDragActive) return;
            if (isPageSettingsMode()) {
                autoSavePageSettings(true);
                return;
            }

            autoSaveAndPreview(true);
        }

        
        window.autoSaveAndRefresh = autoSaveAndRefresh;
        window.autoSaveAndPreview = autoSaveAndPreview;
        window.refreshElement = refreshElement;

    

    

    $(document).on('click', '.card-next-indicator', function(e) {
        e.stopPropagation();
        var id = $(this).data('id');
        var $card = $('.impulse-page-card[data-id="' + id + '"]');

        var currentNext = String($card.data('next-sequence') || '');
        var seqPages = (Impulse.pages || []).filter(function(p){ return String(p.id) !== String(id); });
        var h = '<div class="impulse-context-label">NEXT SCENE</div>';
        h += ctxItem('grid-set-next-seq:0', 'End here', !currentNext ? '\u2713' : '');
        seqPages.forEach(function(p) {
            var check = String(p.id) === currentNext ? '\u2713' : '';
            h += ctxItem('grid-set-next-seq:' + p.id, escapeHtml(p.name), check);
        });
        window._ctxData = { gridCard: { id: id, name: $card.find('.name-text').text(), slug: $card.data('slug') } };
        var rect = this.getBoundingClientRect();
        ctxShow($('#impulse-context-menu'), rect.left, rect.bottom + 2, h);
    });

        

        pageSettingsSaveTimer = null;
        function autoSavePageSettings(needsRefresh) {
            if (!isPageSettingsMode()) return;
            window._impulsePageEdited = true;   
            _doSavePageSettings(needsRefresh);
        }

        function saveScreenBarSettings(needsRefresh) {
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            _doSavePageSettings(needsRefresh);

            if (_smA) _saveScreenEnvSettings();
        }

        

        

        

        
        
        var _lastPersistedPageSettings = null;
        var _pageHistoryOldSnap = null;
        var _pageHistoryTimer = null;

        function _doSavePageSettings(needsRefresh) {
            clearTimeout(pageSettingsSaveTimer);
            showSaveStatus(true);

            
            if (_lastPersistedPageSettings === null) {
                _lastPersistedPageSettings = JSON.parse(JSON.stringify(Impulse.pageSettings || {}));
            }

            
            if (!_pageHistoryOldSnap && !isUndoRedo) {
                _pageHistoryOldSnap = JSON.parse(JSON.stringify(_lastPersistedPageSettings));
            }

            var existingSettings = Impulse.pageSettings || {};
            var settings = collectSettingsFromPanel(existingSettings);

            
            ['animation_layers'].forEach(function(key) {
                if (typeof settings[key] === 'string') {
                    try { settings[key] = JSON.parse(settings[key]); } catch(e) {}
                }
            });

            $('#impulse-settings-body .impulse-color-text').each(function() {
                var name = $(this).attr('name');
                var val = $(this).val();
                if (name && val) {
                    settings[name] = val;
                }
            });

            
            var _savedCloudEff = $('input[name="screen_cloud_effect"]').val() || 'none';
            var _bgLockedSave = ['cosmos','neon','caustics','glass','bubble','flow','aurora','clouds','aura','topography','lava','blob','fractal','noise','ripple','swirl','kaleidoscope','turing'];
            
            var _effBgKey = 'screen_' + _savedCloudEff + '_bg_color';
            var $barBg = $('#impulse-screen-bar input[name="' + _effBgKey + '"].impulse-color-text');
            if ($barBg.length && $barBg.val() && _bgLockedSave.indexOf(_savedCloudEff) === -1) {
                settings[_effBgKey] = $barBg.val();
            }

            ['', '_tablet', '_mobile'].forEach(function(suffix) {
                var sidesKey = 'padding_sides' + suffix;
                if (settings[sidesKey] !== undefined) {
                    settings['padding_left' + suffix] = settings[sidesKey];
                    settings['padding_right' + suffix] = settings[sidesKey];
                }
            });

            Impulse.pageSettings = settings;
            
            $('.impulse-panel-right').data('existing-settings', settings);

            if (!needsRefresh) {
                applyPageSettingsToPreview(settings);
            }
            
            pageSettingsSaveTimer = setTimeout(function() {
                var _settingsSnapshotForAjax = JSON.parse(JSON.stringify(Impulse.pageSettings || {}));
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: Impulse.pageSettings }),
                    success: function() {
                        showSaveStatus();

                        
                        
                        _lastPersistedPageSettings = _settingsSnapshotForAjax;
                        if (needsRefresh) {
                            refreshPreview();
                        }
                    },
                    error: function() {
                        showSaveStatus();
                    }
                });
            }, needsRefresh ? 0 : 300);

            

            
            clearTimeout(_pageHistoryTimer);
            _pageHistoryTimer = setTimeout(function() {
                var oldSnap = _pageHistoryOldSnap;
                _pageHistoryOldSnap = null;
                if (!oldSnap || isUndoRedo || typeof saveToHistory !== 'function') return;
                var newSnap = JSON.parse(JSON.stringify(Impulse.pageSettings || {}));
                var oldJ = JSON.stringify(oldSnap);
                var newJ = JSON.stringify(newSnap);
                if (oldJ === newJ) return;  
                saveToHistory('page_settings_update', {
                    oldSettings: oldSnap,
                    newSettings: newSnap
                });
            }, 500);
        }

        function updateElementSettings(id, newSettings) {
            if (!id) return;
            showSaveStatus(true);
            enqueueSave(id, newSettings, function(success) {
                if (!success) return;
                
                if ($('.impulse-panel-right').data('element-id') == id) {
                    $('.impulse-panel-right').data('existing-settings', newSettings);
                }
                showSaveStatus();
                
                if (selectedElementType) {
                    renderSettingsPanel(selectedElementType, newSettings);
                }
                refreshPreview();
            });
        }

        $(document).on('blur', '.impulse-panel-right input[type="text"], .impulse-panel-right textarea', function() {
            
            if ($(this).hasClass('impulse-unfold-title') || $(this).hasClass('impulse-unfold-content')) return;
            
            if (selectedElementType === 'title' && ($('input[name="la_preset"]').val() || '')) return;
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) {
                if (isPageSettingsMode()) {
                    autoSavePageSettings(false);
                }
                return;
            }

            if (deletePending[id]) return;
            if (isPageSettingsMode()) return;
            if ($('#impulse-settings-body').text().indexOf('Loading') !== -1) return;
            
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            var settings = collectSettingsFromPanel(existingSettings);
            var mergedSettings = $.extend({}, existingSettings, settings);
            
            enqueueSave(id, mergedSettings, function(success) {
                if (!success) return;
                
                if ($('.impulse-panel-right').data('element-id') == id) {
                    $('.impulse-panel-right').data('existing-settings', mergedSettings);
                }
                showSaveStatus();
                
                var type = selectedElementType;
                var elConfig = window.ImpulseElementConfig ? window.ImpulseElementConfig.get(type) : null;
                var structuralList = elConfig ? (elConfig.structural || []) : [];
                if (structuralList.length > 0) {
                    var changed = false;
                    for (var i = 0; i < structuralList.length; i++) {
                        if (JSON.stringify(existingSettings[structuralList[i]]) !== JSON.stringify(mergedSettings[structuralList[i]])) {
                            changed = true; break;
                        }
                    }
                    if (changed) refreshPreview();
                }
            });
        });

        $(document).on('click', '.impulse-panel-right button[name="enable_modal"]', function() {
            var $btn = $(this);
            var $input = $btn.siblings('input[type="hidden"][name="enable_modal"]');
            var isOn = $input.val() === '1';
            var nowOn = !isOn;
            $input.val(nowOn ? '1' : '');
            $btn.attr('data-value', nowOn ? 'true' : 'false');
            $btn.text('PRODUCT CARD ' + (nowOn ? 'ON' : 'OFF'));
            $btn.css({
                background: nowOn ? ''+ImpC.white+'' : ''+ImpC.panel+'',
                color:      nowOn ? ''+ImpC.surface2+'' : ''+ImpC.dim+''
            });
            
            var cached = $('.impulse-panel-right').data('existing-settings') || {};
            cached.enable_modal = nowOn;
            $('.impulse-panel-right').data('existing-settings', cached);
            
            if (nowOn) {
                window._impulseQvPreviewElementId = null; 
                postToIframe({ type: 'impulse-quickview-preview-open' });
            } else {
                postToIframe({ type: 'impulse-quickview-preview-close' });
            }
            
            autoSaveAndPreview(true);
        });

        $(document).on('change', '.impulse-panel-right input[type="checkbox"], #impulse-screen-bar input[type="checkbox"]', function() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id && !isPageSettingsMode()) return;

            var name = $(this).attr('name');

            if (name === 'screen_infinite_loop') {
                var _loopOn = $(this).is(':checked');
                saveScreenBarSettings(false);
                
                if (Impulse.pageSettings) Impulse.pageSettings.screen_infinite_loop = _loopOn ? '1' : '0';

                

                
                try {
                    var _ifr = document.getElementById('impulse-iframe');
                    var _iwin = _ifr && _ifr.contentWindow;
                    var _idoc = _ifr && _ifr.contentDocument;
                    if (_idoc && _idoc.body) {
                        if (_loopOn) _idoc.body.setAttribute('data-screen-infinite', '1');
                        else         _idoc.body.removeAttribute('data-screen-infinite');
                    }
                    if (_iwin && _iwin.ImpulseScreens && typeof _iwin.ImpulseScreens.updateSettings === 'function') {
                        
                        _iwin.ImpulseScreens.updateSettings(undefined, undefined, undefined, undefined, undefined, _loopOn);
                    }
                } catch (_e) {}
                return;
            }

            if (name === 'la_flash' || name === 'la_scroll_trigger') {
                return; 
            }

            if (name === 'modal_design_show_desc' && $(this).is(':checked')) {
                $('input[name="modal_design_show_long_desc"]').prop('checked', false);
            }
            if (name === 'modal_design_show_long_desc' && $(this).is(':checked')) {
                $('input[name="modal_design_show_desc"]').prop('checked', false);
            }

            if ($(this).attr('name') === 'stretch') {
                if ($(this).is(':checked')) {
                    $('.impulse-border-radius-setting').hide();
                } else {
                    
                    var contentWidth = parseInt($('input[name="content_width"]').val()) || 100;
                    if (contentWidth < 100) {
                        $('.impulse-border-radius-setting').show();
                    }
                }
            }

            if ($(this).attr('name') === 'autoplay') {
                if ($(this).is(':checked')) {
                    $('.impulse-autoplay-settings').css({opacity:'', 'pointer-events':''});
                    $('.impulse-autoplay-speed-slider').show();
                    $('.impulse-transition-standalone').hide();
                } else {
                    $('.impulse-autoplay-settings').css({opacity:'0.4', 'pointer-events':'none'});
                    $('.impulse-autoplay-speed-slider').hide();
                    $('.impulse-transition-standalone').show();
                }
            }

            if ($(this).attr('name') === 'transparent') {
                if ($(this).is(':checked')) {
                    $('.impulse-transparent-options').show();
                } else {
                    $('.impulse-transparent-options').hide();
                }
            }

            
            
            if (name === 'tiles_number') {
                var _tnId = $('.impulse-panel-right').data('element-id');
                var _tnIframe = document.getElementById('impulse-iframe');
                if (_tnIframe && _tnIframe.contentDocument && _tnId) {
                    var _tnNums = _tnIframe.contentDocument.querySelectorAll('.impulse-el[data-id="' + _tnId + '"] .impulse-acc-tile-num');
                    var _tnShow = $(this).is(':checked');
                    _tnNums.forEach(function(n) { n.style.display = _tnShow ? '' : 'none'; });
                }
                
                if (_tnId) refreshElement(_tnId);
                autoSaveAndPreview(true);
                return;
            }

            if ($(this).attr('name') === 'hover_highlight') {
                var checked = $(this).is(':checked');
                $('.impulse-hh-effect-row').toggle(checked);
                $('.impulse-hh-duration-wrap').toggle(checked);
            }

            if ($(this).attr('name') === 'announcement_enabled') {
                if ($(this).is(':checked')) {
                    $('.impulse-announcement-options').show();
                    $('.impulse-announcement-color').show();
                } else {
                    $('.impulse-announcement-options').hide();
                    $('.impulse-announcement-color').hide();
                }
            }

            if ($(this).attr('name') === 'show_cta') {
                if ($(this).is(':checked')) {
                    $('.impulse-cta-options').show();
                    $('.impulse-cta-color').show();
                } else {
                    $('.impulse-cta-options').hide();
                    $('.impulse-cta-color').hide();
                }
            }

            if ($(this).attr('name') === 'show_cart') {
                $('.impulse-cart-url-option').toggle($(this).is(':checked'));
            }

            if ($(this).attr('name') === 'show_account') {
                $('.impulse-account-url-option').toggle($(this).is(':checked'));
            }

            if ($(this).attr('name') === 'show_site_name') {
                if ($(this).is(':checked')) {
                    $('.impulse-site-name-options').show();
                } else {
                    $('.impulse-site-name-options').hide();
                }
            }

            if ($(this).attr('name') === 'show_logo') {
                if ($(this).is(':checked')) {
                    $('.impulse-footer-logo-options').show();
                } else {
                    $('.impulse-footer-logo-options').hide();
                }
            }

            if ($(this).attr('name') === 'bg_animation_enabled') {
                if ($(this).is(':checked')) {
                    $('.impulse-bg-animation-settings').show();

                    
                    var $ac = $('.impulse-section-anim-layers-container').first();
                    if ($ac.length && $ac.children('.impulse-section-anim-layer').length === 0) {
                        $('.impulse-add-section-anim-layer').first().trigger('click');
                    }
                } else {
                    $('.impulse-bg-animation-settings').hide();
                }
            }

            if ($(this).attr('name') === 'depth_of_field') {
                $('.impulse-dt-dof-settings').css({opacity: $(this).is(':checked') ? '' : '0.35', 'pointer-events': $(this).is(':checked') ? '' : 'none'});
            }

            if ($(this).attr('name') === 'show_newsletter') {
                if ($(this).is(':checked')) {
                    $('.impulse-footer-newsletter-options').show();
                } else {
                    $('.impulse-footer-newsletter-options').hide();
                }
            }

            if ($(this).attr('name') === 'show_payments') {
                if ($(this).is(':checked')) {
                    $('.impulse-footer-payment-options').show();
                } else {
                    $('.impulse-footer-payment-options').hide();
                }
            }

            if ($(this).attr('name') === 'fill_container') {
                var _fcOn = $(this).is(':checked');
                $('#impulse-image-size-controls').toggle(!_fcOn);
                $('#impulse-image-focal').toggle(_fcOn);
            }

            

            

            if ($(this).attr('name') === 'lightbox_enabled') {
                if ($(this).is(':checked')) {
                    $('#impulse-image-standard-controls').hide();
                    $('#impulse-image-lightbox-controls').show();
                } else {
                    $('#impulse-image-lightbox-controls').hide();
                    $('#impulse-image-standard-controls').show();
                }
            }

            
            
            if ($('#impulse-settings-body').text().indexOf('Loading') !== -1) return;

            

            

            
            
            if (isPageSettingsMode()) {
                var screenVisualNames = ['screen_tunnel','nav_dots','screen_infinite_loop','hero_loop'];
                var chkName = $(this).attr('name') || '';
                if (screenVisualNames.indexOf(chkName) !== -1) {
                    var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
                    Impulse.pageSettings = settings;
                    applyPageSettingsToPreview(settings);
                    reinitTunnelFromSettings(settings);
                    autoSavePageSettings(false);
                } else {
                    autoSavePageSettings(true);
                }
                return;
            }

            if ($(this).closest('.impulse-section-anim-layer').length) return;

            if ($(this).attr('name') === 'tiles_num') {
                var _tnShow = $(this).is(':checked');
                var _tnId = $('.impulse-panel-right').data('element-id');
                var _tnIframe = document.getElementById('impulse-iframe');
                if (_tnIframe && _tnIframe.contentDocument && _tnId) {
                    _tnIframe.contentDocument.querySelectorAll('.impulse-el[data-id="' + _tnId + '"] .impulse-acc-tile-num').forEach(function(n) {
                        n.style.display = _tnShow ? '' : 'none';
                    });
                }
                autoSaveAndPreview();
                return;
            }

            autoSaveAndPreview(true);
        });

        
        function reinitTunnelFromSettings(settings) {
            var ifrm = document.getElementById('impulse-iframe');
            var IS = ifrm && ifrm.contentWindow && ifrm.contentWindow.ImpulseScreens;
            if (IS && IS.reinitTunnel) {
                var tunnelOn = settings.screen_tunnel == '1' || settings.screen_tunnel === true;
                IS.reinitTunnel(
                    tunnelOn,
                    tunnelOn ? 'none' : (settings.screen_cloud_effect || 'none'),
                    tunnelOn,
                    parseFloat(settings.screen_tunnel_speed) || 1
                );
            } else if (ifrm) {
                
                var _ps = settings;
                ifrm.addEventListener('load', function _rr() {
                    ifrm.removeEventListener('load', _rr);
                    setTimeout(function() {
                        var IS2 = ifrm.contentWindow && ifrm.contentWindow.ImpulseScreens;
                        if (IS2 && IS2.reinitTunnel) {
                            var t2 = _ps.screen_tunnel == '1' || _ps.screen_tunnel === true;
                            IS2.reinitTunnel(t2, t2 ? 'none' : (_ps.screen_cloud_effect || 'none'), t2, parseFloat(_ps.screen_tunnel_speed) || 1);
                        }
                    }, 200);
                });
            }
        }

        

        $(document).on('input', 'input[name="screen_outer_opacity"]', function() {
            var v = Math.max(0, Math.min(100, parseInt($(this).val()) || 0)) / 100;
            var ifrm = document.getElementById('impulse-iframe');
            var fx = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
            if (fx && fx.update) fx.update({ outerOpacity: v });
        });

        var _effectSettingsCache = {};
        
        var _3dColorEffects = ['cosmos','particles','crystal','blob','wormhole','fractal','bubbles','caustics','glass','bubble','fireflies','flow','aurora','clouds','aura','topography','fireflies','plexus','neon','noise','grid','dots','ripple','swirl','kaleidoscope','columns','nebula'];
        function _cacheCurrentEffectColors() {
            var curEff = $('input[name="screen_cloud_effect"]').val() || 'none';
            if (_3dColorEffects.indexOf(curEff) === -1) return;
            _effectSettingsCache[curEff] = {
                c1: $('input[name="screen_3d_color1"]').val() || '',
                c2: $('input[name="screen_3d_color2"]').val() || '',
                c3: $('input[name="screen_3d_color3"]').val() || '',
                c4: $('input[name="screen_3d_color4"]').val() || '',
                spd: $('input[name="screen_3d_speed"]').val() || '',
                int: $('input[name="screen_3d_intensity"]').val() || '',
                preset: $('input[name="screen_3d_preset"]').val() || '',
                bg: $('#impulse-screen-bar input[name="bg_color"]').val() || ''
            };
        }
        function _restoreEffectColors(eff, settings) {
            if (_3dColorEffects.indexOf(eff) === -1) return;
            var cached = _effectSettingsCache[eff];
            if (!cached) {
                
                settings.screen_3d_color1 = '#333333';
                settings.screen_3d_color2 = '#999999';
                settings.screen_3d_color3 = '#666666';
                settings.screen_3d_color4 = '#cccccc';
                settings.screen_3d_speed = '5';
                settings.screen_3d_intensity = '5';
                settings.screen_3d_preset = '';
                return;
            }
            if (cached.c1) settings.screen_3d_color1 = cached.c1;
            if (cached.c2) settings.screen_3d_color2 = cached.c2;
            if (cached.c3) settings.screen_3d_color3 = cached.c3;
            if (cached.c4) settings.screen_3d_color4 = cached.c4;
            if (cached.spd) settings.screen_3d_speed = cached.spd;
            if (cached.int) settings.screen_3d_intensity = cached.int;
            if (cached.preset) settings.screen_3d_preset = cached.preset;
            if (cached.bg) settings.bg_color = cached.bg;
        }
        
        $(document).on('click', '.impulse-effect-btn', function() {
            var val = $(this).data('value');

            
            if (val === undefined) return;
            var isActive = $(this).hasClass('active');

            _cacheCurrentEffectColors();

            $(this).closest('.impulse-effect-presets-wrap, #impulse-screen-bar').find('.impulse-effect-btn').removeClass('active');
            if (!isActive) $(this).addClass('active');

            var effectVal = val;
            if (val === 'clouds') {
                effectVal = 'clouds';
            }

            var newEff = isActive ? 'none' : effectVal;
            $('input[name="screen_cloud_effect"]').val(newEff);

            

            

            if (Impulse.pageSettings) Impulse.pageSettings.screen_cloud_effect = newEff;
            
            if (newEff !== 'depth_image' && Impulse.pageSettings) {
                Impulse.pageSettings._last_env_effect = newEff;
            }

            

            
            
            var _hadDepthImg = $('input[name="screen_depth_image"]').val() || (Impulse.pageSettings && Impulse.pageSettings.screen_depth_image);
            if (_hadDepthImg && newEff !== 'depth_image') {
                $('input[name="screen_depth_image"]').val('');
                $('input[name="screen_depth_map"]').val('');
                $('input[name="screen_depth_enabled"]').val('');

                
                if (Impulse.pageSettings) { Impulse.pageSettings.screen_depth_image = ''; Impulse.pageSettings.screen_depth_map = ''; Impulse.pageSettings.screen_depth_enabled = ''; }
                var _ifrDP = document.getElementById('impulse-iframe');
                var _winDP = _ifrDP && _ifrDP.contentWindow;
                if (_winDP) {
                    var _docDP = _ifrDP.contentDocument || _winDP.document;
                    if (_docDP && _docDP.body) {
                        _docDP.body.removeAttribute('data-depth-image');
                        _docDP.body.removeAttribute('data-depth-map');
                        _docDP.body.removeAttribute('data-depth-strength');
                    }
                    var _wrapDP2 = _docDP && _docDP.querySelector('.impulse-screen-wrapper');
                    if (_wrapDP2) { delete _wrapDP2.dataset.depthImage; }
                    if (_winDP.ImpulseDepthParallax && _winDP.ImpulseDepthParallax.destroyAll) {
                        try { _winDP.ImpulseDepthParallax.destroyAll(); } catch (_e) {}
                    }
                }
            }

            var _smActive = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smActive) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            
            _restoreEffectColors(newEff, settings);
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            reinitTunnelFromSettings(settings);
            
            if (typeof window.populateEnvPresets === 'function') {
                setTimeout(function() {
                    window.populateEnvPresets(Impulse.pageSettings || {});

                    

                    
                    
                    if ($('#impulse-settings-title').text() === 'Environment'
                        && typeof window._showZoneSettings === 'function') {
                        window._showZoneSettings('hero');
                    }
                    saveScreenBarSettings(false);
                    if (newEff === 'depth_image' && !$('input[name="screen_depth_image"]').val()) {
                        setTimeout(function() { if (typeof _open3dPicker === 'function') _open3dPicker(); }, 50);
                    }
                }, 50);
            } else {
                saveScreenBarSettings(false);
            }
            
            setTimeout(function() {
                var ifrm2 = document.getElementById('impulse-iframe');
                var instFx2 = ifrm2 && ifrm2.contentWindow && ifrm2.contentWindow._impulseFX;
                if (instFx2 && instFx2.update) {
                    var newEff = $('input[name="screen_cloud_effect"]').val();
                    var c1, c2;

                    
                    
                    var _peC1 = newEff ? $('input[name="screen_' + newEff + '_color1"]').val() : '';
                    var _peC2 = newEff ? $('input[name="screen_' + newEff + '_color2"]').val() : '';
                    if (_peC1 || _peC2) {
                        c1 = _peC1 || '#000000';
                        c2 = _peC2 || '#333333';
                    } else if (newEff === 'lava') {
                        c1 = $('input[name="screen_lava_color1"]').val() || '#333333';
                        c2 = $('input[name="screen_lava_color2"]').val() || '#999999';
                    } else if (newEff === 'wave') {
                        c1 = $('input[name="screen_wave_color1"]').val() || '#333333';
                        c2 = $('input[name="screen_wave_color2"]').val() || '#999999';
                    } else {
                        c1 = $('input[name="screen_3d_color1"]').val() || '#000000';
                        c2 = $('input[name="screen_3d_color2"]').val() || '#333333';
                    }
                    var _bgForEff = (Impulse.pageSettings && Impulse.pageSettings['screen_' + newEff + '_bg_color']) || '';

                    var _c3val = (newEff ? $('input[name="screen_' + newEff + '_color3"]').val() : '') || $('input[name="screen_3d_color3"]').val() || '';

                    
                    
                    var _updateOpts = { color1: c1, color2: c2 };

                    

                    var _hasC3Uniform = (newEff === 'nebula' || newEff === 'flow');
                    if (_hasC3Uniform) {
                        if (_c3val) _updateOpts.color3 = _c3val;
                        
                        var _bodyBg = '';
                        try { _bodyBg = (ifrm2.contentDocument && ifrm2.contentDocument.body && ifrm2.contentDocument.body.dataset.pageBgColor) || ''; } catch(e) {}
                        _updateOpts.bgColor = _bgForEff || _bodyBg || '#000000';
                    } else {
                        
                        _updateOpts.bgColor = _bgForEff || _c3val || '#666666';
                    }
                    instFx2.update(_updateOpts);
                    
                    if (_bgForEff && ifrm2.contentDocument && ifrm2.contentDocument.body) {
                        ifrm2.contentDocument.body.setAttribute('data-page-bg-color', _bgForEff);
                        ifrm2.contentDocument.body.dataset.pageBgColor = _bgForEff;
                    }
                }
            }, 300);
        });
        $(document).on('click', '.impulse-space-variant-btn', function() {
            var svVal = $(this).data('variant');
            var wasActive = $(this).hasClass('active');
            $('.impulse-space-variant-btn').removeClass('active').css('border-color', ''+ImpC.border+'');
            if (wasActive) {
                
                svVal = '0';
            } else {
                $(this).addClass('active').css('border-color', ''+ImpC.white+'');
            }
            $('input[name="screen_space_variant"]').val(svVal);
            var _svIframe = document.getElementById('impulse-iframe');
            if (_svIframe && _svIframe.contentWindow) {
                _svIframe.contentWindow.postMessage({ type: 'impulse-space-variant', variant: String(svVal) }, '*');
            }
            if (!isPageSettingsMode()) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_mouse_sens_level"]', function() {
            var rawVal = Math.round(parseFloat($(this).val()));
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text(rawVal);
            var sensVal = rawVal / 10;
            var ifrm = document.getElementById('impulse-iframe');
            var ifrBody = ifrm && ifrm.contentDocument && ifrm.contentDocument.body;
            if (ifrBody) ifrBody.dataset.screenMouseSensLevel = sensVal.toFixed(2);
            
            var inst3d = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulse3D;
            if (inst3d && inst3d._sensitivity !== undefined) inst3d._sensitivity = sensVal;
            
            var instFx = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
            if (instFx && instFx.update) instFx.update({mouse: sensVal});
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });
        $(document).on('input change', 'input[name="screen_bw_element_size"]', function() {
            var val = parseInt($(this).val());
            $(this).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(val + '%');
            var ifrm = document.getElementById('impulse-iframe');
            var ifrBody = ifrm && ifrm.contentDocument && ifrm.contentDocument.body;
            if (ifrBody) ifrBody.dataset.screenBwElementSize = String(val);
            var sw = ifrm && ifrm.contentDocument && ifrm.contentDocument.querySelector('.impulse-screen-wrapper');
            if (sw) sw.dataset.bwElementSize = String(val);
            if (!isPageSettingsMode()) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });
        $(document).on('input change', 'input[name="screen_bw_element_count"]', function() {
            var val = parseInt($(this).val());
            $(this).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(val + '%');
            var ifrm = document.getElementById('impulse-iframe');
            var ifrBody = ifrm && ifrm.contentDocument && ifrm.contentDocument.body;
            if (ifrBody) ifrBody.dataset.screenBwElementCount = String(val);
            var sw = ifrm && ifrm.contentDocument && ifrm.contentDocument.querySelector('.impulse-screen-wrapper');
            if (sw) sw.dataset.bwElementCount = String(val);
            if (!isPageSettingsMode()) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });
        $(document).on('change', 'input[name="screen_tunnel_fill"]', function() {
            if (!isPageSettingsMode()) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            reinitTunnelFromSettings(settings);
            saveScreenBarSettings(false);
        });
        $(document).on('input change', 'input[name="screen_bw_accent_color"]', function() {
            var val = $(this).val() || '';
            var ifrm = document.getElementById('impulse-iframe');
            var ifrBody = ifrm && ifrm.contentDocument && ifrm.contentDocument.body;
            if (ifrBody) ifrBody.dataset.screenBwAccentColor = val;
            var sw = ifrm && ifrm.contentDocument && ifrm.contentDocument.querySelector('.impulse-screen-wrapper');
            if (sw) sw.dataset.bwAccentColor = val;
            if (!isPageSettingsMode()) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('click', '.impulse-particles-bg-toggle .impulse-color-swatch', function(e) {
            e.stopPropagation();
            e.preventDefault();
            var $input = $(this).closest('.impulse-color-setting').find('input[name="bg_color"]');
            var cur = ($input.val() || '#000000').toLowerCase();
            var newBg = (cur === '#000000') ? '#ffffff' : '#000000';
            var isDark = newBg === '#000000';
            $input.val(newBg);
            $(this).css('--swatch-color', newBg);
            
            var ifrm = document.getElementById('impulse-iframe');
            if (ifrm && ifrm.contentDocument) {
                var iBody = ifrm.contentDocument.body;
                var iHtml = ifrm.contentDocument.documentElement;
                if (iBody) { iBody.style.setProperty('background', newBg, 'important'); iBody.setAttribute('data-page-bg-color', newBg); }
                if (iHtml) iHtml.style.setProperty('background', newBg, 'important');
                
                var inst3d = ifrm.contentWindow && ifrm.contentWindow._impulse3D;
                if (inst3d && inst3d.updateBlendMode) inst3d.updateBlendMode(isDark);
            }
            if (Impulse.pageSettings) Impulse.pageSettings.bg_color = newBg;
            saveScreenBarSettings(false);
            
            $('.impulse-color-picker').removeClass('open');
        });

        
        
        $(document).on('input change', 'input[name="bg_color_2"], input[name="bg_color_3"], input[name="bg_color_4"]', function() {
            var any = false;
            ['bg_color_2','bg_color_3','bg_color_4'].forEach(function(k){
                var v = ($('input[name="' + k + '"]').val() || '').trim();
                if (v && v !== 'transparent' && v.indexOf('rgba(0,0,0,0)') !== 0) any = true;
            });
            $('.impulse-section-mesh-wrap').css('display', any ? 'block' : 'none');
        });

        

        

        
        
        $(document).on('input change', 'input[name="gradient_overlay_color1"], input[name="gradient_overlay_color2"]', function() {
            var alive = function (c) {
                if (!c || c === 'transparent') return false;
                if (c.indexOf('rgba(0,0,0,0)') === 0) return false;
                return true;
            };
            var c1 = ($('input[name="gradient_overlay_color1"]').val() || '').trim();
            var c2 = ($('input[name="gradient_overlay_color2"]').val() || '').trim();
            $('.impulse-section-overlay-sliders').css('display', (alive(c1) || alive(c2)) ? 'block' : 'none');
        });

        

        $(document).on('input change', 'input[name="text_gradient_to"]', function() {
            var v = ($(this).val() || '').trim();

            
            
            var visible = false;
            if (v && v !== 'transparent') {
                var m = v.match(/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([\d.]+))?\s*\)/i);
                var a = m && m[1] !== undefined && m[1] !== '' ? parseFloat(m[1]) : 1;
                visible = a > 0.02;
            }
            $('.impulse-text-grad-wrap').css('display', visible ? 'block' : 'none');
        });

        

        

        
        
        $(document).on('input change',
            '#impulse-settings-body input[name="color"],' +
            '#impulse-settings-body input[name="text_gradient_to"],' +
            '#impulse-settings-body input[name="text_gradient_angle"]',
            function() {
                var type = $('.impulse-panel-right').data('element-type') || selectedElementType;
                if (type !== 'text') return;
                var id = $('.impulse-panel-right').data('element-id');
                if (!id) return;
                var iframe = document.getElementById('impulse-iframe');
                if (!iframe || !iframe.contentDocument) return;
                var elWrap = iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                if (!elWrap) return;
                var outer = elWrap.querySelector('.impulse-text');
                if (!outer) return;

                
                var inner = outer.querySelector('[contenteditable], [data-field="content"]') || outer;

                var color  = ($('input[name="color"]').val()             || '#1d2327').trim();
                var gradTo = ($('input[name="text_gradient_to"]').val()  || '').trim();
                var angle  = parseInt($('input[name="text_gradient_angle"]').val(), 10);
                if (isNaN(angle)) angle = 135;

                var hasGrad = false;
                if (gradTo && gradTo !== 'transparent') {
                    var m = gradTo.match(/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([\d.]+))?\s*\)/i);
                    var a = m && m[1] !== undefined && m[1] !== '' ? parseFloat(m[1]) : 1;
                    hasGrad = a > 0.02;
                }

                
                
                outer.style.setProperty('--imp-text-grad-angle', angle + 'deg');

                if (hasGrad) {
                    inner.style.setProperty('background-image',
                        'linear-gradient(var(--imp-text-grad-angle, ' + angle + 'deg), ' + color + ', ' + gradTo + ')');
                    inner.style.setProperty('-webkit-background-clip', 'text');
                    inner.style.setProperty('background-clip', 'text');
                    inner.style.setProperty('color', 'transparent');
                    inner.style.setProperty('-webkit-text-fill-color', 'transparent');

                    
                    inner.setAttribute('data-fill', 'gradient');
                    inner.setAttribute('data-grad-1', color);
                    inner.setAttribute('data-grad-2', gradTo);
                } else {

                    
                    inner.style.removeProperty('background-image');
                    inner.style.removeProperty('-webkit-background-clip');
                    inner.style.removeProperty('background-clip');
                    inner.style.removeProperty('color');
                    inner.style.removeProperty('-webkit-text-fill-color');
                    inner.removeAttribute('data-fill');
                    inner.removeAttribute('data-grad-1');
                    inner.removeAttribute('data-grad-2');

                    outer.style.setProperty('color', color);
                }
            }
        );

        

        
        $(document).on('input change', '#impulse-settings-body input[name="bg_color"]', function() {
            if (!isPageSettingsMode()) return;
            var bgVal = $(this).val() || '' + ImpC.light + '';
            var ifrm = document.getElementById('impulse-iframe');
            if (ifrm && ifrm.contentDocument) {
                var iBody = ifrm.contentDocument.body;
                var iHtml = ifrm.contentDocument.documentElement;
                if (iBody) {
                    iBody.style.setProperty('background', bgVal, 'important');
                    iBody.setAttribute('data-page-bg-color', bgVal);
                    iBody.dataset.pageBgColor = bgVal;
                }
                if (iHtml) iHtml.style.setProperty('background', bgVal, 'important');
                var inst3d = ifrm.contentWindow && ifrm.contentWindow._impulse3D;
                if (inst3d && inst3d.updateBgColor) inst3d.updateBgColor(bgVal);
                var instWave = ifrm.contentWindow && ifrm.contentWindow._impulseWave;
                if (instWave && instWave.updateBgColor) instWave.updateBgColor(bgVal);
                var instFx = ifrm.contentWindow && ifrm.contentWindow._impulseFX;
                if (instFx && instFx.update) instFx.update({ bgColor: bgVal });
            }
            if (Impulse.pageSettings) Impulse.pageSettings.bg_color = bgVal;
            autoSavePageSettings(false);
        });

        $(document).on('input change',
            'input[name="screen_lava_color1"], input[name="screen_lava_color2"], input[name="screen_lava_color3"], input[name="screen_lava_color4"]',
            function() {
            var _curEff = $('input[name="screen_cloud_effect"]').val() || 'lava';
            var ifrm = document.getElementById('impulse-iframe');
            var mg = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseMotionLava;
            if (mg) {
                mg.updateColors([
                    $('input[name="screen_lava_color1"]').val() || '#333333',
                    $('input[name="screen_lava_color2"]').val() || '#999999',
                    $('input[name="screen_lava_color3"]').val() || '#666666',
                    $('input[name="screen_lava_color4"]').val() || '#cccccc'
                ]);
            }
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_lava_intensity"]', function() {
            var rawVal = parseInt($(this).val()) || 5;
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text(rawVal);
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var ifrm = document.getElementById('impulse-iframe');
            var mg = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseMotionLava;
            if (mg) {
                var _curEff2 = $('input[name="screen_cloud_effect"]').val() || 'lava';
                var _baseAmp = 320;
                var _factor = 0.5 + (rawVal - 1) / 9.0;
                mg.amp = Math.round(_baseAmp * _factor);
            }
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_lava_speed"]', function() {
            var rawVal = parseInt($(this).val()) || 10;
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text((rawVal / 10).toFixed(1));
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var ifrm = document.getElementById('impulse-iframe');
            var mg = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseMotionLava;
            if (mg) mg.updateSpeed(rawVal / 10);
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        
        function _buildOverlayCss(diameter, roundness, angle, softness, c1, c2) {
            
            var _isOff = function(c) {
                if (!c) return true;
                var s = String(c).toLowerCase();
                if (s === 'transparent' || s === 'rgba(0,0,0,0)') return true;
                var m = s.match(/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([\d.]+))?\s*\)/);
                if (m && m[1] !== undefined) return parseFloat(m[1]) <= 0.02;
                return false;
            };
            if (_isOff(c1) && _isOff(c2)) return '';

            
            var d  = Math.max(10, Math.min(200, parseInt(diameter)  || 100));
            var r  = Math.max(0,  Math.min(100, parseInt(roundness) || 100));
            var ag = ((parseInt(angle) || 0) % 360 + 360) % 360;
            var sf = Math.max(0,  Math.min(100, parseInt(softness)  || 100));
            
            var rx = (d / 2);                                     
            var ry = Math.max(0.5, rx * (r / 100));
            
            var inner = Math.max(0,   (100 - sf) / 2);
            var outer = Math.min(100, 100 - inner);
            return 'background: radial-gradient(ellipse ' + rx.toFixed(2) + '% ' + ry.toFixed(2) + '% at center, '
                 + c1 + ' 0%, ' + c1 + ' ' + inner.toFixed(2) + '%, '
                 + c2 + ' ' + outer.toFixed(2) + '%, ' + c2 + ' 100%);'
                 + 'transform: translate(-50%, -50%) rotate(' + ag + 'deg);';
        }

        
        
        function _liveUpdateGradientOverlay() {
            var ifrm = document.getElementById('impulse-iframe');
            if (!ifrm || !ifrm.contentDocument) return;
            var doc = ifrm.contentDocument;
            var diameter  = $('input[name="screen_gradient_diameter"]').val();
            var roundness = $('input[name="screen_gradient_roundness"]').val();
            var angle     = $('input[name="screen_gradient_angle"]').val();
            var softness  = $('input[name="screen_gradient_softness"]').val();
            var color1    = $('input[name="screen_gradient_color1"]').val() || 'rgba(0,0,0,0)';
            var color2    = $('input[name="screen_gradient_color2"]').val() || 'rgba(0,0,0,0)';
            
            if (diameter  === undefined || diameter  === '') diameter  = 100;
            if (roundness === undefined || roundness === '') roundness = 100;
            if (angle     === undefined || angle     === '') angle     = 0;
            if (softness  === undefined || softness  === '') softness  = 100;

            var goEl = doc.querySelector('.impulse-gradient-overlay');
            var css  = _buildOverlayCss(diameter, roundness, angle, softness, color1, color2);
            if (!css) { if (goEl) goEl.remove(); return; }
            if (!goEl) {
                goEl = doc.createElement('div');
                goEl.className = 'impulse-gradient-overlay';
                doc.body.appendChild(goEl);
            }

            
            goEl.style.cssText =
                'position:fixed;top:50%;left:50%;width:200%;height:200%;'
              + 'pointer-events:none;z-index:1;'
              + css;
        }
        $(document).on('input change',
            'input[name="screen_gradient_color1"], input[name="screen_gradient_color2"],'
          + 'input[name="screen_gradient_diameter"], input[name="screen_gradient_roundness"],'
          + 'input[name="screen_gradient_angle"], input[name="screen_gradient_softness"]',
          function() {
            _liveUpdateGradientOverlay();
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_wave_color1"], input[name="screen_wave_color2"], input[name="screen_wave_color3"], input[name="screen_wave_color4"]', function() {
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var ifrm = document.getElementById('impulse-iframe');
            var wv = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseWave;
            if (wv) {
                wv.updateColors([
                    $('input[name="screen_wave_color1"]').val() || '#6b8eff',
                    $('input[name="screen_wave_color2"]').val() || '#e256a0',
                    $('input[name="screen_wave_color3"]').val() || '#ff8054',
                    $('input[name="screen_wave_color4"]').val() || '#9333ea'
                ]);
            }
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_wave_speed"]', function() {
            var rawVal = parseInt($(this).val()) || 10;
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text((rawVal / 10).toFixed(1));
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var ifrm = document.getElementById('impulse-iframe');
            var wv = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseWave;
            if (wv) wv.updateSpeed(rawVal / 10);
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('click', '.impulse-wave-preset-btn', function() {
            var preset = $(this).data('value');
            $('.impulse-wave-preset-btn').removeClass('active').css({'background':''+ImpC.panel+'','color':''+ImpC.muted+''});
            $(this).addClass('active').css({'background':''+ImpC.white+'','color':''+ImpC.surface2+''});
            $('input[name="screen_wave_preset"]').val(preset);

            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var ifrm = document.getElementById('impulse-iframe');
            var wv = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseWave;
            
            var _presetColors = {
                flow:  ['#6b8eff','#e256a0','#ff8054','#9333ea'],  
                storm: ['#ffffff','#cccccc','#555555','#1a1a1a'],  
                helix: ['#041e42','#0077b6','#00b4d8','#caf0f8'],  
                vortex:['#ffdd00','#ff6b35','#d90429','#6a040f'],  
                aurora:['#1b1b4e','#762c9e','#06d6a0','#ffd166']   
            };
            var pColors = _presetColors[preset];
            if (pColors) {
                var _swN = ['screen_wave_color1','screen_wave_color2','screen_wave_color3','screen_wave_color4'];
                for (var _si = 0; _si < 4; _si++) {
                    $('input[name="' + _swN[_si] + '"]').val(pColors[_si]);
                    $('input[name="' + _swN[_si] + '"]').closest('.impulse-color-setting').find('.impulse-color-swatch').each(function(){
                        this.style.setProperty('--swatch-color', pColors[_si]);
                    });
                }
                if (wv) wv.updateColors(pColors);
            }
            if (wv) wv.updatePreset(preset);
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_wave_intensity"]', function() {
            var rawVal = parseInt($(this).val()) || 5;
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text(rawVal);
            var _smA = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smA) return;
            var ifrm = document.getElementById('impulse-iframe');
            var wv = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseWave;
            if (wv) wv.updateIntensity(rawVal / 3.33); 
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_cloud_coverage"], input[name="screen_cloud_feather"], input[name="screen_cloud_opacity"]', function() {
            var ifrm = document.getElementById('impulse-iframe');
            var inst3d = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulse3D;
            if (!inst3d || !inst3d._cvMat) return;
            var cov   = parseInt($('input[name="screen_cloud_coverage"]').val()) || 4;
            var feath = parseInt($('input[name="screen_cloud_feather"]').val())  || 5;
            var opc   = parseInt($('input[name="screen_cloud_opacity"]').val())  || 4;
            
            inst3d._cvMat.uniforms.u_cov.value   = 0.65 - cov   * 0.030;  
            inst3d._cvMat.uniforms.u_feath.value = 0.08 + feath * 0.032;  
            inst3d._cvMat.uniforms.u_opc.value   = opc === 0 ? 0.0 : (2.0 + opc * 1.8);  
            
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text($(this).val());
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            saveScreenBarSettings(false);
        });

        $(document).on('click', '.impulse-3d-preset-btn', function() {
            var preset = $(this).data('value');
            $('.impulse-3d-preset-btn').removeClass('active').css({'background':''+ImpC.panel+'','color':''+ImpC.muted+''});
            $(this).addClass('active').css({'background':''+ImpC.white+'','color':''+ImpC.surface2+''});
            $('input[name="screen_3d_preset"]').val(preset);
            var _smActive = Impulse.pageSettings && (true);
            if (!isPageSettingsMode() && !_smActive) return;
            var ifrm = document.getElementById('impulse-iframe');
            var inst3d = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulse3D;
            if (inst3d) inst3d.updatePreset(preset);
            
            var I3D = ifrm && ifrm.contentWindow && ifrm.contentWindow.Impulse3D;
            var curEff = $('input[name="screen_cloud_effect"]').val();
            
            var _fxColors = {
                wave:{flow:['#6b8eff','#e256a0','#ff8054','#9333ea'],storm:['#ffffff','#cccccc','#555555','#1a1a1a'],helix:['#041e42','#0077b6','#00b4d8','#caf0f8'],vortex:['#ffdd00','#ff6b35','#d90429','#6a040f'],aurora:['#1b1b4e','#762c9e','#06d6a0','#ffd166']},

                

                caustics:{pool:['#0a3a6a','#a8ecff'],deep_sea:['#001833','#1abcff'],tropical_c:['#003a2a','#7affcd'],golden:['#3a1a00','#ffd070'],arctic:['#1a3344','#e8f6ff']},
                glass:{crystal:['#1a1a2e','#4466aa'],liquid:['#0a1a2a','#44aacc'],diamond:['#1a0a2a','#8844cc'],cube_g:['#0a1a2a','#3388bb'],ring_g:[''+ImpC.surface2+'','#6688aa']},

                

                

                

                
                
                flow:{ink_flow:['#0a0a3a','#22ccff','#e0ffff'],lava_f:['#1a0033','#ff3380','#ffe0aa'],ocean_f:['#001a2a','#3cdde0','#eaffff'],neon_fl:['#0a0014','#ff2bbf','#00ffee'],smoke_f:['#1a1a1e','#999aaa','#dddddd']},
                topography:{terrain_t:['#22aa66','#88ddaa'],ocean_t:['#0044aa','#44aaff'],volcanic_t:['#cc2200','#ff8844'],arctic_t:['#4488cc','#ccddee'],forest_t:['#114422','#44aa44']},

                
                
                fractal:{classic:['#ff0066','#ffcc00'],fire_f:['#ff3300','#ffaa00'],ice_f:['#0044ff','#88ddff'],neon_f:['#ff00cc','#00ffaa'],mono_f:['#1a1a1a','#dddddd']},
                dots:{ink:['#1a1a1a','#666666'],neon:['#00ffcc','#ff00cc'],violet:['#2a1a44','#cc88ff'],fire:['#331100','#ff6600'],light:['#cccccc','#ffffff']},
                ripple:{pond:['#0a1a1a','#00ddaa'],ocean_rp:['#ff4400','#ffaa00'],mercury_rp:['#1a1a1a','#cccccc'],neon_rp:['#110022','#cc00ff'],mono_rp:['#000000','#ffffff']},

                

                

                
                
                swirl:{vortex:['#0066ff','#ffffff','#000010'],galaxy_sw:['#a040ff','#ff80ff','#0a0014'],fire_sw:['#ff3300','#ffcc00','#100000'],ice_sw:['#3399ff','#ccffff','#001830'],mono_sw:['#888888','#ffffff','#0a0a0a']},

                

                

                nebula:{orion:['#ff4488','#88ddff','#000814'],crab:['#cc44ff','#00eecc','#08000a'],helix_n:['#00cc88','#ffee44','#00141a'],rosette:['#ff6644','#ffcc66','#100600']},
                kaleidoscope:{crystal_k:['#cc4400','#004488'],psyche:['#cc0099','#009966'],stained:['#aa8800','#0044aa'],neon_k:['#00aa44','#aa0044'],mono_k:['#ffffff','#000000']},
                membrane:{tissue:['#2a1a1a','#aa8888'],coral:['#2a0a1a','#cc6688'],fungal:['#1a2a1a','#88aa77'],neon_m:['#0a1a2a','#44ccaa'],mono_m:['#222222','#999999']},

                

                

                
                neon:{
                    cyber_n: ['#00ccff','#000814'],  
                    neon_n:  ['#ff66cc','#0a0014'],  
                    fire_n:  ['#ff8c22','#0a0200'],  
                    ice_n:   ['#aaccff','#040810'],  
                    mono_n:  ['#dddddd','#080808']   
                },
                grid:{cyber_g:['#001133','#0088ff','#000a1a'],matrix_g:['#001a00','#00ff44','#000800'],fire_g:['#1a0500','#ff6622','#0d0200'],ice_g:['#0a1a2a','#66ccee','#050d14']},
                aura:{
                    sunset_au:['#ff6600','#aa0066'],
                    ocean_au:['#0066aa','#00ffcc'],
                    neon_au:['#ff00cc','#00ff44'],
                    forest_au:['#006622','#88ff44'],
                    mono_au:['#222222','#dddddd']
                },
                aurora:{borealis:['#00ff88','#cc44ff','#ff44aa'],twilight_a:['#ff0088','#4400ff','#00ffcc'],polar_a:['#00ffcc','#0044ff','#ff8800'],tropic_a:['#00ff44','#ff6600','#0088ff'],solar_a:['#ff8800','#ff0055','#ffcc00']},
                clouds:{dawn_c:['#ffaacc','#aabbff','#ffddaa'],spring_c:['#aaffcc','#ccaaff','#ffeeaa'],dusk_c:['#ffbbaa','#cc88ff','#aaddff'],ocean_c:['#aaddff','#88ffcc','#ccaaff'],rose_c:['#ffaadd','#ffccaa','#aabbff']},
                
                lava:{
                    volcano:  ['#ff2200','#ffcc00','#0022ff','#00ffcc'],  
                    electric: ['#00aaff','#ff00cc','#ffff00','#00ff44'],  
                    acid:     ['#aaff00','#ff4400','#0000ff','#ff00aa'],  
                    blood:    ['#cc0022','#004488','#ffaa00','#00cc88'],  
                    aurora_l: ['#00ffaa','#aa00ff','#ff6600','#0066ff']   
                },
                bubble:{ocean:['#0044aa','#00ccee'],aurora_bu:['#001a00','#00ffaa'],dusk_bu:['#220033','#8844ff'],fire_bu:['#330000','#ff4400'],crystal_bu:['#1a1a2e','#8899cc']},

                

                
                noise:{
                    marble:   ['#0f0f10','#f3eee4'],  
                    wood:     ['#2a1808','#c89968'],  
                    ocean_nf: ['#001f3f','#5cb8ff'],  
                    magma_nf: ['#1a0400','#ff5a0c'],  
                    mint:     ['#0a2818','#8effba']   
                },

                agate:{amethyst:['#7733cc','#cc88ff'],tourmaline:['#ff4488','#88ff44'],aquamarine:['#00aacc','#88eeff'],citrine:['#ffcc00','#ff8800']},
                storm:{sahara:['#cc8833','#664400'],dust_devil:['#44aaee','#0033aa'],sirocco:['#8855cc','#442266'],haboob:['#bb2200','#220500']},
                lens:{milky_way:['#ddeeff','#4466aa'],andromeda:['#ffeecc','#cc6633'],deep_field:['#ffffff','#888888'],quasar:['#ffffff','#ff00cc']},
                turing:{leopard:['#100800','#e8c840'],coral:['#001018','#00ddee'],mitosis:['#080010','#cc00ff'],stripes:['#0a0500','#ff3300']}
                };
            
            var _3dColors = {
                columns:{
                    city:    ['#0a0a1a','#0d2244','#1155aa','#22aaff'],
                    ember:   ['#0a0000','#660000','#ff4400','#ffcc00'],
                    crystal: ['#0a0022','#220066','#8833ff','#eeddff'],
                    ocean:   ['#000a14','#002244','#006688','#00ccaa'],
                    chrome:  ['#0a0a10','#222230','#667788','#aabbcc']
                },
                particles:{
                    spark: ['#ff0044','#0044ff','#ffcc00','#00cc88','#ffffff'],
                    glow:  ['#00ccff','#ff4400','#cc00ff','#88ff00','#ffffff'],
                    prism: ['#ff0066','#00ccff','#ffcc00','#00ff88','#ffffff']
                },
                plexus:{
                    sky:     ['#3366ff','#aaccff','#f0f4ff'],  
                    crimson: ['#ff2200','#555555','#000000'],  
                    mint:    ['#00cc88','#99ffdd','#f0fff8'],  
                    gold:    ['#ffcc00','#554400','#000000'],  
                    violet:  ['#9966ff','#ddbbff','#f8f0ff']   
                },
                fireflies:{warm:['#364a1d','#459fff','#213bff','#d40000'],cool:['#aaddff','#66bbff','#3388ff','#0055cc'],forest:['#ddff99','#88ee55','#44bb33','#117722'],violet:['#eebbff','#bb77ff','#8844dd','#5511aa']},
                wormhole:{spacetime:['#1a1a44','#4444aa','#8888cc','#ccccee'],void_hole:['#0a0a1e','#222244','#444466','#666688'],fire_vortex:['#1a0000','#aa2200','#ff4400','#ffaa44'],ice_vortex:['#0a1a2a','#2266aa','#44aadd','#aaddee'],neon_warp:['#0a002e','#6622cc','#cc44ff','#ff88ff']},
                bubbles:{iridescent:['#4466aa','#aabbcc'],soap:['#334466','#99aacc'],glass_b:['#1a2a3a','#8899bb'],neon_b:['#ff00cc','#00ffcc'],frost_b:['#4488aa','#aaccdd']},
                };

            

            

            var _noColorPresets = [];
            var _fxEffList = ['lava','wave','fractal','caustics','glass','bubble','fireflies','flow','aurora','clouds','aura','topography','neon','noise','grid','dots','ripple','swirl','kaleidoscope','membrane','nebula','agate','storm','lens','turing'];
            var _3dEffList = ['plexus','fireflies','particles','crystal','blob','wormhole','bubbles','cosmos','columns','asteroid','grid'];

            if (_3dEffList.indexOf(curEff) !== -1 && _3dColors[curEff] && _3dColors[curEff][preset]) {
                
                var pc = _3dColors[curEff][preset];

                var _isAllColor = (curEff === 'fireflies');
                var _pcBg = (!_isAllColor && pc[pc.length-1] && typeof pc[pc.length-1]==='string' && pc.length >= 3 && pc[pc.length-1].charAt(0)==='#' && (pc.length > 4 || (pc.length===3 && pc[2].charAt(0)==='#'))) ? pc[pc.length-1] : null;

                
                var _sn3d = ['screen_'+curEff+'_color1','screen_'+curEff+'_color2','screen_'+curEff+'_color3','screen_'+curEff+'_color4'];
                for (var _i3 = 0; _i3 < Math.min(_isAllColor ? 4 : 2, pc.length); _i3++) {
                    if (!pc[_i3]) continue;
                    $('input[name="' + _sn3d[_i3] + '"]').val(pc[_i3]);
                    $('input[name="' + _sn3d[_i3] + '"]').closest('.impulse-color-setting').find('.impulse-color-swatch').each(function(){
                        this.style.setProperty('--swatch-color', pc[_i3]);
                    });
                }
                
                if (_pcBg) {
                    var _ifrm2 = document.getElementById('impulse-iframe');
                    var _doc2 = _ifrm2 && _ifrm2.contentDocument;
                    if (_doc2) _doc2.body.style.background = _pcBg;
                    if (inst3d && inst3d.updateBgColor) inst3d.updateBgColor(_pcBg);
                    
                    var _ifrm2fx = document.getElementById('impulse-iframe');
                    var _instFx2 = _ifrm2fx && _ifrm2fx.contentWindow && _ifrm2fx.contentWindow._impulseFX;
                    if (_instFx2 && _instFx2.update) _instFx2.update({ bgColor: _pcBg });
                    
                    $('#impulse-screen-bar input[name="bg_color"]').val(_pcBg).trigger('change');
                }
                
                var _pcColors = pc.filter(function(v){ return v && typeof v === 'string' && v.charAt(0) === '#'; });
                if (inst3d) inst3d.updateColors(_pcColors);
            } else if (_3dEffList.indexOf(curEff) !== -1 && I3D && I3D.EFFECTS) {
                
                var effDef = I3D.EFFECTS[curEff];
                if (effDef && effDef.presets && effDef.presets[preset]) {
                    var pc = effDef.presets[preset].colors || [];

                
                var _sn3d = ['screen_'+curEff+'_color1','screen_'+curEff+'_color2','screen_'+curEff+'_color3','screen_'+curEff+'_color4'];
                    for (var _i3 = 0; _i3 < Math.min(4, pc.length); _i3++) {
                        $('input[name="' + _sn3d[_i3] + '"]').val(pc[_i3]);
                        $('input[name="' + _sn3d[_i3] + '"]').closest('.impulse-color-setting').find('.impulse-color-swatch').each(function(){
                            this.style.setProperty('--swatch-color', pc[_i3]);
                        });
                    }
                    if (inst3d) inst3d.updateColors(pc);
                }
            } else if (_fxEffList.indexOf(curEff) !== -1 && _fxColors[curEff] && _fxColors[curEff][preset] && _noColorPresets.indexOf(curEff) === -1) {
                var fpc = _fxColors[curEff][preset];

                

                

                var _colorNames;
                if (curEff === 'lava') {
                    _colorNames = ['screen_lava_color1','screen_lava_color2','screen_lava_color3','screen_lava_color4'];
                } else if (curEff === 'wave') {
                    _colorNames = ['screen_wave_color1','screen_wave_color2','screen_wave_color3','screen_wave_color4'];
                } else {
                    _colorNames = ['screen_'+curEff+'_color1','screen_'+curEff+'_color2','screen_'+curEff+'_color3','screen_'+curEff+'_color4'];
                }
                for (var _i3 = 0; _i3 < 4; _i3++) {
                    if (fpc[_i3] === undefined) continue;
                    $('input[name="' + _colorNames[_i3] + '"]').val(fpc[_i3]);
                    $('input[name="' + _colorNames[_i3] + '"]').closest('.impulse-color-setting').find('.impulse-color-swatch').each(function(){
                        this.style.setProperty('--swatch-color', fpc[_i3]);
                    });
                }
                var instFx = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
                if (instFx && instFx.update) {

                    
                    if (curEff === 'nebula' || curEff === 'flow') {
                        instFx.update({color1: fpc[0], color2: fpc[1], color3: fpc[2] || undefined});
                    } else {
                        instFx.update({color1: fpc[0], color2: fpc[1], bgColor: fpc[2] || undefined});
                    }
                }

                
                var _fxBgLocked2 = ['aurora','clouds','aura','topography','neon','noise','grid','dots','ripple','swirl','kaleidoscope','flow','bubble','caustics','glass','fractal','nebula','turing'];
                var _fxPcBg = (fpc[2] && typeof fpc[2]==='string' && fpc[2].charAt(0)==='#' && _fxBgLocked2.indexOf(curEff) === -1) ? fpc[2] : null;
                if (_fxPcBg) {
                    var _fxBgIfrm = document.getElementById('impulse-iframe');
                    if (_fxBgIfrm && _fxBgIfrm.contentDocument) _fxBgIfrm.contentDocument.body.style.background = _fxPcBg;
                    if (instFx && instFx.update) instFx.update({bgColor: _fxPcBg});
                    $('#impulse-screen-bar input[name="bg_color"]').val(_fxPcBg);
                    $('input[name="bg_color"].impulse-color-text').closest('.impulse-color-setting').find('.impulse-color-swatch').each(function(){ this.style.setProperty('--swatch-color', _fxPcBg); });
                }
            }
            
            var _presetSliders = {
                lava:{volcano:{spd:6},acid:{spd:7},blood:{spd:4},aurora_l:{spd:5}},
                wave:{ocean_w:{spd:5,int:5},ember_w:{spd:6,int:7},aurora_w:{spd:4,int:5},chrome_w:{spd:3,int:4},neon_w:{spd:6,int:6}},
                caustics:{pool:{spd:5,int:5},deep_sea:{spd:3,int:4},tropical_c:{spd:6,int:6},golden:{spd:4,int:5},arctic:{spd:3,int:3}},
                glass:{crystal:{spd:3,shape:1},liquid:{spd:5,shape:5},diamond:{spd:3,shape:1},cube_g:{spd:4,shape:2},ring_g:{spd:4,shape:3}},
                flow:{ink_flow:{spd:4,int:5},lava_f:{spd:3,int:7},ocean_f:{spd:5,int:4},neon_fl:{spd:6,int:6},smoke_f:{spd:3,int:3}},
                topography:{terrain_t:{spd:4,int:5},ocean_t:{spd:3,int:4},volcanic_t:{spd:5,int:7},arctic_t:{spd:2,int:3},forest_t:{spd:4,int:5}},
                plexus:{sky:{spd:4,int:5},crimson:{spd:4,int:5},mint:{spd:5,int:5},gold:{spd:3,int:5},violet:{spd:4,int:4}},
                fireflies:{warm:{spd:5,int:5},cool:{spd:4,int:5},violet:{spd:5,int:4}},
                wormhole:{spacetime:{spd:5,int:5},void_hole:{spd:3,int:7},fire_vortex:{spd:7,int:6},ice_vortex:{spd:4,int:4},neon_warp:{spd:6,int:5}},
                dots:{ink:{spd:4,int:5},neon:{spd:5,int:6},violet:{spd:5,int:5},fire:{spd:6,int:7},light:{spd:4,int:5}},
                ripple:{pond:{spd:4,int:4},ocean_rp:{spd:5,int:5},mercury_rp:{spd:3,int:6},neon_rp:{spd:6,int:5},mono_rp:{spd:4,int:4}},

                

                
                
                swirl:{vortex:{spd:4,int:12},galaxy_sw:{spd:3,int:15},fire_sw:{spd:8,int:14},ice_sw:{spd:3,int:8},mono_sw:{spd:4,int:6}},

                
                nebula:{orion:{spd:5,int:11},crab:{spd:6,int:13},helix_n:{spd:4,int:10},rosette:{spd:5,int:14}},
                kaleidoscope:{crystal_k:{spd:4,int:4},psyche:{spd:6,int:6},stained:{spd:3,int:5},neon_k:{spd:5,int:5},mono_k:{spd:4,int:4}},
                membrane:{tissue:{spd:2,int:3},coral:{spd:4,int:8},fungal:{spd:1,int:9},neon_m:{spd:8,int:6},mono_m:{spd:2,int:2}},
                fractal:{classic:{spd:4,int:5},fire_f:{spd:5,int:7},ice_f:{spd:3,int:4},neon_f:{spd:6,int:6},mono_f:{spd:4,int:4}},
                neon:{cyber_n:{spd:5,int:5},neon_n:{spd:6,int:7},fire_n:{spd:7,int:6},ice_n:{spd:4,int:5},mono_n:{spd:4,int:3}},
                grid:{cyber_g:{spd:5,int:5},matrix_g:{spd:6,int:6},fire_g:{spd:6,int:7},ice_g:{spd:4,int:5}},
                aura:{sunset_au:{spd:4,int:5},ocean_au:{spd:3,int:5},neon_au:{spd:6,int:7},forest_au:{spd:4,int:5},mono_au:{spd:3,int:4}},
                aurora:{borealis:{spd:4,int:5},twilight_a:{spd:5,int:6},polar_a:{spd:3,int:4},tropic_a:{spd:4,int:5},solar_a:{spd:6,int:7}},
                clouds:{dawn_c:{spd:3,int:4},spring_c:{spd:4,int:5},dusk_c:{spd:3,int:5},ocean_c:{spd:4,int:4},rose_c:{spd:3,int:5}},
                bubbles:{iridescent:{spd:3,int:5},soap:{spd:4,int:5},glass_b:{spd:2,int:4},neon_b:{spd:5,int:6},frost_b:{spd:3,int:4}},
                bubble:{ocean:{spd:4,int:5},aurora_bu:{spd:3,int:5},dusk_bu:{spd:5,int:6},fire_bu:{spd:6,int:7},crystal_bu:{spd:3,int:4}},
                noise:{marble:{spd:3,int:5},wood:{spd:2,int:6},ocean_nf:{spd:4,int:5},magma_nf:{spd:5,int:7},mint:{spd:3,int:4}},
                storm:{sahara:{spd:4,int:5},dust_devil:{spd:6,int:7},sirocco:{spd:5,int:6},haboob:{spd:7,int:8}},
                agate:{amethyst:{spd:3,int:6},tourmaline:{spd:4,int:5},aquamarine:{spd:3,int:5},citrine:{spd:4,int:6}},
                lens:{milky_way:{spd:3,int:5},andromeda:{spd:4,int:6},deep_field:{spd:2,int:4},quasar:{spd:5,int:7}},
                asteroid:{inner_belt:{spd:4,int:5},saturn:{spd:3,int:6},kuiper:{spd:2,int:4},diamonds:{spd:5,int:7}},
                turing:{leopard:{spd:4,int:5},coral:{spd:3,int:6},mitosis:{spd:5,int:5},stripes:{spd:4,int:6}}
            };
            if (_presetSliders[curEff] && _presetSliders[curEff][preset]) {
                var ps = _presetSliders[curEff][preset];
                var _spdName = curEff === 'lava' ? 'screen_lava_speed' : curEff === 'wave' ? 'screen_wave_speed' : 'screen_3d_speed';
                var _intName = curEff === 'wave' ? 'screen_wave_intensity' : 'screen_3d_intensity';
                var $spdSlider = $('input[name="' + _spdName + '"]');
                var $intSlider = $('input[name="' + _intName + '"]');
                if (ps.spd != null) $spdSlider.val(ps.spd).closest('.impulse-setting-row').find('.impulse-slider-value').text(ps.spd);
                var curInt = parseInt($intSlider.val()) || 5;
                var newInt = ps.int != null ? ps.int : curInt;
                if (ps.int != null) $intSlider.val(newInt).closest('.impulse-setting-row').find('.impulse-slider-value').text(newInt);
                var updateOpts = {speed: (ps.spd != null ? ps.spd : parseInt($spdSlider.val()) || 5)/10, intensity: newInt/10};
                if (ps.shape != null) updateOpts.shape = ps.shape;
                
                if (_3dEffList.indexOf(curEff) !== -1) {
                    if (inst3d) { if (ps.spd != null) inst3d.updateSpeed(updateOpts.speed); if (ps.int != null) inst3d.updateIntensity(updateOpts.intensity); }
                } else {
                    var instFx2 = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
                    if (instFx2 && instFx2.update) instFx2.update(updateOpts);
                }
                if (ps.shape != null) $('input[name="screen_prism_shape"]').val(ps.shape);
            }
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            reinitTunnelFromSettings(settings);
            saveScreenBarSettings(false);
        });

        

        

        $(document).on('input change', 'input[name="screen_3d_speed"], input[name^="screen_"][name$="_speed"]', function() {
            var nameAttr = $(this).attr('name') || '';

            if (nameAttr === 'screen_lava_speed' || nameAttr === 'screen_wave_speed' ||
                nameAttr === 'screen_tunnel_speed' || nameAttr === 'screen_mouse_sens_level') return;
            var rawVal = parseInt($(this).val()) || 5;
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text(rawVal);
            if (!isPageSettingsMode() && !(Impulse.pageSettings && (true))) return;
            var speedVal = rawVal / 10;
            var ifrm = document.getElementById('impulse-iframe');
            var inst3d = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulse3D;
            if (inst3d) inst3d.updateSpeed(speedVal);
            var instFx = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
            if (instFx && instFx.update) instFx.update({speed: speedVal});
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('input change', 'input[name="screen_3d_intensity"], input[name^="screen_"][name$="_intensity"]', function() {
            var nameAttr = $(this).attr('name') || '';
            if (nameAttr === 'screen_lava_intensity' || nameAttr === 'screen_wave_intensity') return;
            var rawVal = parseInt($(this).val()) || 5;
            $(this).closest('.impulse-setting-row').find('.impulse-slider-value').text(rawVal);
            if (!isPageSettingsMode() && !(Impulse.pageSettings && (true))) return;
            var ifrm = document.getElementById('impulse-iframe');
            var inst3d = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulse3D;
            if (inst3d) inst3d.updateIntensity(rawVal / 10);
            var instFx = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
            if (instFx && instFx.update) instFx.update({intensity: rawVal / 10});
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            saveScreenBarSettings(false);
        });

        
        $(document).on('click', '.impulse-neon-shape', function() {
            var sides = $(this).data('sides');
            $('.impulse-neon-shape').removeClass('active');
            $(this).addClass('active');
            $('input[name="screen_neon_sides"]').val(sides);
            if (!isPageSettingsMode() && !(Impulse.pageSettings && (true))) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            reinitTunnelFromSettings(settings);
            saveScreenBarSettings(false);
        });

        $(document).on('click', '.impulse-cloud-schema-btn', function() {
            var schema = $(this).data('schema');
            $('.impulse-cloud-schema-btn').removeClass('active');
            $(this).addClass('active');
            $('input[name="screen_cloud_effect"]').val(schema);
            $('.impulse-cloud-schema-val').val($(this).data('index'));
            if (!isPageSettingsMode() && !(Impulse.pageSettings && (true))) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            reinitTunnelFromSettings(settings);
            saveScreenBarSettings(false);
        });

        

        
        $(document).on('click', '.impulse-prism-select-bg', function() {
            if (typeof _open3dPicker === 'function') {
                _open3dPicker();
            }
        });

        

        $(document).on('click', '.impulse-prism-remove-bg', function() {
            $('input[name="screen_prism_bg"]').val('');
            $('input[name="screen_depth_image"]').val('');
            $('input[name="screen_depth_map"]').val('');
            $('input[name="screen_depth_enabled"]').val('0');

            
            var _dsRemEarly = collectSettingsFromPanel(Impulse.pageSettings || {});
            _dsRemEarly.screen_prism_bg = '';
            _dsRemEarly.screen_depth_image = '';
            _dsRemEarly.screen_depth_map = '';
            _dsRemEarly.screen_depth_enabled = '0';
            Impulse.pageSettings = _dsRemEarly;
            if (typeof window.populateEnvPresets === 'function') {
                window.populateEnvPresets(_dsRemEarly);
            }
            var ifrm = document.getElementById('impulse-iframe');
            var instFx = ifrm && ifrm.contentWindow && ifrm.contentWindow._impulseFX;
            if (instFx && instFx.update) instFx.update({bgImage: ''});
            
            if (ifrm && ifrm.contentWindow) {
                var _ifrDocRem = ifrm.contentDocument || ifrm.contentWindow.document;
                var _wrapRem = _ifrDocRem && _ifrDocRem.querySelector('.impulse-screen-wrapper');
                if (_wrapRem) {
                    _wrapRem.dataset.depthImage = '';
                    _wrapRem.dataset.depthMap = '';
                    _wrapRem.dataset.prismBg = '';
                    _wrapRem.removeAttribute('data-depth-enabled');
                }
                if (_ifrDocRem && _ifrDocRem.body) {
                    _ifrDocRem.body.removeAttribute('data-depth-image');
                    _ifrDocRem.body.removeAttribute('data-depth-map');
                    _ifrDocRem.body.removeAttribute('data-depth-strength');
                    _ifrDocRem.body.removeAttribute('data-depth-enabled');
                }

                if (ifrm.contentWindow.ImpulseDepthParallax && ifrm.contentWindow.ImpulseDepthParallax.destroyAll) {
                    ifrm.contentWindow.ImpulseDepthParallax.destroyAll();
                }
            }
            
            $('.impulse-3d-presets-section').css({opacity:'','pointer-events':''});
            saveScreenBarSettings(false);

            var _dsRem = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = _dsRem;
            if (typeof reinitTunnelFromSettings === 'function') {
                reinitTunnelFromSettings(_dsRem);
            }
        });

        $(document).on('change', 'input[name="screen_bw_hue_color"]', function() {
            var hex = $(this).val();
            
            var r=parseInt(hex.slice(1,3),16)/255,g=parseInt(hex.slice(3,5),16)/255,b=parseInt(hex.slice(5,7),16)/255;
            var mx=Math.max(r,g,b),mn=Math.min(r,g,b),h=0;
            if(mx!==mn){var d=mx-mn;h=mx===r?((g-b)/d+(g<b?6:0))/6:mx===g?((b-r)/d+2)/6:((r-g)/d+4)/6;}
            var hue=Math.round(h*360);
            $('input[name="screen_effect_hue"]').val(hue);
            if (!isPageSettingsMode() && !(Impulse.pageSettings && (true))) return;
            var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
            Impulse.pageSettings = settings;
            applyPageSettingsToPreview(settings);
            reinitTunnelFromSettings(settings);
            autoSavePageSettings(false);
        });

        
        
        function _dataURLtoBlob(dataUrl) {
            var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1];
            var bstr = atob(arr[1]), n = bstr.length, u8 = new Uint8Array(n);
            while (n--) u8[n] = bstr.charCodeAt(n);
            return new Blob([u8], { type: mime });
        }

        function _depthSpinner($btn) {
            if (!window._impulseDepthSpinnerCss) {
                window._impulseDepthSpinnerCss = true;
                $('<style>@keyframes impulse-depth-spin{to{transform:rotate(360deg)}}</style>').appendTo('head');
            }
            var _svg = '<svg width="11" height="11" viewBox="0 0 11 11" style="animation:impulse-depth-spin 0.75s linear infinite;vertical-align:middle;margin-right:5px;flex-shrink:0" fill="none"><circle cx="5.5" cy="5.5" r="4.5" stroke="'+ImpC.dim+'" stroke-width="1.5"/><path d="M5.5 1A4.5 4.5 0 0 1 10 5.5" stroke="#ccc" stroke-width="1.5" stroke-linecap="round"/></svg>';
            if ($btn && $btn.length) {
                $btn.prop('disabled', true).html(_svg + 'Generating…');
            }
        }

        

        

        
        function _depthProgress(show) {
            var ID = 'impulse-depth-progress';
            var el = document.getElementById(ID);
            if (!show) { if (el && el.parentNode) el.parentNode.removeChild(el); return; }
            if (!window._impulseDepthSpinnerCss) {
                window._impulseDepthSpinnerCss = true;
                $('<style>@keyframes impulse-depth-spin{to{transform:rotate(360deg)}}</style>').appendTo('head');
            }
            if (el) return;
            el = document.createElement('div');
            el.id = ID;
            el.setAttribute('style', 'position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:2147483646;display:flex;align-items:center;gap:9px;background:#1a1d21;border:1px solid #2a2e33;color:#e0e0e0;font-size:12px;line-height:1.2;padding:11px 16px;border-radius:6px;box-shadow:0 6px 24px rgba(0,0,0,0.45);pointer-events:none');
            el.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" style="animation:impulse-depth-spin 0.75s linear infinite;flex-shrink:0" fill="none"><circle cx="7" cy="7" r="6" stroke="#555" stroke-width="2"/><path d="M7 1A6 6 0 0 1 13 7" stroke="#ccc" stroke-width="2" stroke-linecap="round"/></svg>'
                + '<span>Calculating depth map. This can take a few minutes.</span>';
            document.body.appendChild(el);
        }

        function _runDepthGenerate(imageUrl, $btn) {
            if (!imageUrl) return;

            
            
            if (!Impulse.isStandalone) {
                (window.showToast || function(){})('Depth map generation is not available in this build.', 'error');
                return;
            }
            _depthSpinner($btn);
            _depthProgress(true);
            var _resetBtn = function() {
                if ($btn && $btn.length) $btn.prop('disabled', false).html('Generate Depth');
            };
            var _fail = function(msg) {
                _resetBtn();
                _depthProgress(false);
                console.error('[depth]', msg);
                (window.showToast || function(){})(msg, 'error');
            };
            $.ajax({
                url: (Impulse.siteUrl || '') + '/api/depth-map.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    image_url:   imageUrl,
                    license_key: (Impulse && Impulse.licenseKey) || '',
                    nonce:       (Impulse && Impulse.nonce) || ''
                }),
                timeout: 300000,
                success: function(resp) {
                    if (!resp || !resp.success || !resp.depth_url) {
                        _fail('Depth generation failed: ' + ((resp && resp.error) || 'Unknown error'));
                        return;
                    }
                    
                    fetch(resp.depth_url)
                        .then(function(r) {
                            if (!r.ok) throw new Error('Depth map fetch failed (' + r.status + ')');
                            return r.blob();
                        })
                        .then(function(blob) {
                            var _fd = new FormData();
                            _fd.append('action', 'instinctor_save_depth_map');
                            _fd.append('nonce', window.Impulse.adminNonce);
                            _fd.append('source_url', imageUrl);
                            _fd.append('file', blob, 'depth-map.png');
                            return $.ajax({ url: ajaxurl, method: 'POST', data: _fd, processData: false, contentType: false });
                        })
                        .then(function(ur) {
                            var depthUrl = ur && ur.success && ur.data && ur.data.url ? ur.data.url : resp.depth_url;
                            $('input[name="screen_depth_map"]').val(depthUrl);
                            _resetBtn();
                            _depthProgress(false);
                            (window.showToast || function(){})('Depth map generated', 'success');
                            
                            var _ds = collectSettingsFromPanel(Impulse.pageSettings || {});
                            Impulse.pageSettings = _ds;
                            applyPageSettingsToPreview(_ds);
                            saveScreenBarSettings(false);
                            var _ifrEl = document.getElementById('impulse-iframe');
                            if (_ifrEl && _ifrEl.contentWindow && _ifrEl.contentWindow.ImpulseDepthParallax) {
                                var _ifrDoc = _ifrEl.contentDocument || _ifrEl.contentWindow.document;
                                if (_ifrDoc && _ifrDoc.body) {
                                    _ifrDoc.body.setAttribute('data-depth-image',    imageUrl);
                                    _ifrDoc.body.setAttribute('data-depth-map',      depthUrl);
                                    _ifrDoc.body.setAttribute('data-depth-strength', (function(v){ return (v === undefined || v === '') ? '50' : v; })($('input[name="screen_depth_strength"]').val()));
                                    _ifrEl.contentWindow.ImpulseDepthParallax.destroyAll();
                                    _ifrEl.contentWindow.ImpulseDepthParallax.init(_ifrDoc.body);
                                }
                            }
                            if (typeof window.populateEnvPresets === 'function') {
                                setTimeout(function() { window.populateEnvPresets(Impulse.pageSettings || {}); }, 50);
                            }
                            
                            if (typeof reinitTunnelFromSettings === 'function') {
                                reinitTunnelFromSettings(Impulse.pageSettings);
                            }
                        })
                        .catch(function(err) {
                            _fail('Depth map processing failed: ' + (err && err.message ? err.message : 'unknown'));
                        });
                },
                error: function(xhr) {
                    var _msg;
                    if (xhr && xhr.status === 403)      _msg = 'Depth service: not authenticated — re-login and retry';
                    else if (xhr && xhr.status === 404) _msg = 'Depth service not available in this build (requires standalone backend)';
                    else if (xhr && xhr.status)         _msg = 'Depth service error ' + xhr.status;
                    else                                _msg = 'Depth service unavailable. Please try again.';
                    _fail(_msg);
                }
            });
        }

        
        function _saveDepthMapLocally(remoteUrl, sourceImageUrl, callback) {

            

            
            if (!remoteUrl) {

                _runDepthGenerate(sourceImageUrl, null);
                callback('');
                return;
            }

            

            
            
            fetch(remoteUrl, { method: 'HEAD' })
                .then(function(r) { return r.ok; }, function() { return false; })
                .then(function(ok) {
                    if (!ok) {
                        _runDepthGenerate(sourceImageUrl, null);
                        callback('');
                        return;
                    }
                    try {
                        callback(remoteUrl);
                    } catch (e) {

                        console.error('[depth] apply callback failed:', e);
                    }
                });
        }

        function _open3dPicker() {

            _d3InlineCache = null;
            openImglibPicker({ label: 'Select 3D Image', platformCategory: '3d', noFocal: true, noUpload: !Impulse.hasActiveLicense }, function(attachment) {
                var imageUrl = attachment.url;

                

                

                var pairedDepth = attachment.depthUrl || imageUrl.replace(/(\.[^\/\.]+)$/, 'a.png');

                

                var _prevDepthImg = $('input[name="screen_depth_image"]').val() || '';
                var _prevDepthMap = $('input[name="screen_depth_map"]').val() || '';
                $('input[name="screen_depth_image"]').val(imageUrl);
                var _ds = collectSettingsFromPanel(Impulse.pageSettings || {});

                

                

                
                _ds.screen_depth_image = imageUrl;
                Impulse.pageSettings = _ds;
                if (typeof window.populateEnvPresets === 'function') {
                    window.populateEnvPresets(_ds);
                }

                

                var _ifrFX = document.getElementById('impulse-iframe');
                var _ifrWin = _ifrFX && _ifrFX.contentWindow;
                if (_ifrWin && _ifrWin._impulseFX && _ifrWin._impulseFX.update) {
                    _ifrWin._impulseFX.update({ bgImage: imageUrl });
                }
                if (_ifrWin) {
                    var _ifrDocDP = _ifrFX.contentDocument || _ifrWin.document;
                    var _wrapDP = _ifrDocDP && _ifrDocDP.querySelector('.impulse-screen-wrapper');
                    if (_wrapDP) {
                        _wrapDP.dataset.depthImage = imageUrl;
                    }
                }
                if (pairedDepth) {
                    
                    var _dep3dSpinnerFP = '<div class="imp3d-depth-spin" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.45);z-index:4;pointer-events:none;border-radius:2px"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" style="animation:impulse-spin 0.75s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg></div>';
                    $('.impulse-3d-inline-card.active').append(_dep3dSpinnerFP);
                    
                    var _curEffPick = $('input[name="screen_cloud_effect"]').val();
                    if (_curEffPick !== 'glass') {
                        $('input[name="screen_cloud_effect"]').val('depth_image');

                        

                        if (Impulse.pageSettings) Impulse.pageSettings.screen_cloud_effect = 'depth_image';
                    }
                    $('input[name="screen_depth_enabled"]').val('1');
                    if (Impulse.pageSettings) Impulse.pageSettings.screen_depth_enabled = '1';

                    
                    var _applyDepthMap = function(mapUrl) {
                        if (!mapUrl) return;
                        $('input[name="screen_depth_map"]').val(mapUrl);
                        var _ds2 = collectSettingsFromPanel(Impulse.pageSettings || {});
                        Impulse.pageSettings = _ds2;
                        var _ifrEl = document.getElementById('impulse-iframe');
                        if (_ifrEl && _ifrEl.contentWindow && _ifrEl.contentWindow.ImpulseDepthParallax) {
                            var _ifrDoc = _ifrEl.contentDocument || _ifrEl.contentWindow.document;
                            if (_ifrDoc && _ifrDoc.body) {
                                _ifrDoc.body.setAttribute('data-depth-image', imageUrl);
                                _ifrDoc.body.setAttribute('data-depth-map', mapUrl);
                                _ifrDoc.body.setAttribute('data-depth-strength', (function(v){ return (v === undefined || v === '') ? '50' : v; })($('input[name="screen_depth_strength"]').val()));
                                _ifrEl.contentWindow.ImpulseDepthParallax.destroyAll();
                                _ifrEl.contentWindow.ImpulseDepthParallax.init(_ifrDoc.body);
                            }
                        }
                        applyPageSettingsToPreview(_ds2);
                        if (typeof reinitTunnelFromSettings === 'function') reinitTunnelFromSettings(_ds2);
                        saveScreenBarSettings(false);
                    };

                    
                    
                    if (imageUrl === _prevDepthImg && _prevDepthMap && _curEffPick !== 'glass') {
                        _applyDepthMap(_prevDepthMap);
                    }
                    _saveDepthMapLocally(pairedDepth, imageUrl, function(localDepth) {
                        $('.imp3d-depth-spin').remove();
                        if (!localDepth) {

                            

                            if (pairedDepth && !$('input[name="screen_depth_map"]').val()) {
                                _applyDepthMap(pairedDepth);
                            }
                            return;
                        }
                        _applyDepthMap(localDepth);
                    });
                }

                
            });
        }

        
        
        $(document).on('click', '.impulse-depth-pick-image, .impulse-depth-change-btn', function(e) {
            e.stopPropagation();
            e.preventDefault();
            _open3dPicker();
        });

                
        $(document).on('click', '.impulse-depth-generate-btn', function() {
            var imageUrl = $('input[name="screen_depth_image"]').val().trim();
            _runDepthGenerate(imageUrl, $(this));
        });

        $(document).on('input', 'input[name="screen_depth_strength"]', function() {
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-depth-strength', strength: parseInt($(this).val()) / 100 }, '*');
            }
        });

        function _rebuildImgPanel() {
            var elementId = $('.impulse-panel-right').data('element-id');
            var elType = $('.impulse-panel-right').data('element-type');
            if (!elementId || elType !== 'image') return;
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            var newSettings = collectSettingsFromPanel(existingSettings);
            var merged = $.extend({}, existingSettings, newSettings);
            $('.impulse-panel-right').data('existing-settings', merged);
            $('#impulse-settings-body').html(buildSettingsForm('image', merged, []));
            impulseAnimatorSvgAutoLoad();
        }

        
        function _impulseKineticLiveUpdate(elId) {
            if (!elId) {
                elId = ($('.impulse-panel-right').data('element-id')
                     || (typeof impulseSelectedElId === 'function' ? impulseSelectedElId() : null));
            }
            if (!elId) return;
            var ifr = document.getElementById('impulse-iframe');
            if (!ifr || !ifr.contentWindow) return;
            var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
            if (!ifrDoc) return;
            var block = ifrDoc.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-kinetic-block');
            if (!block) return; 
            var $body = $('#impulse-settings-body');

            

            

            
            if ($body.find('[name="composition"]').length === 0) return;
            var composition  = ($body.find('[name="composition"]').val() || 'block-slam');
            var text         = ($body.find('[name="text"]').val()        || '');
            var color        = ($body.find('[name="color"]').val()       || '#ffffff');
            var loop         = $body.find('[name="loop"]').is(':checked') ? '1' : '0';
            var speed        = ($body.find('[name="speed"]').val()       || '1');
            var intensity    = ($body.find('[name="intensity"]').val()   || '1');
            var height       = parseInt($body.find('[name="height"]').val() || '400', 10);
            var customMode   = ($body.find('[name="custom_mode"]').val() || '0');
            var tier         = ($body.find('[name="tier"]').val() || 'hero');
            var lineGap      = ($body.find('[name="line_gap"]').val() || '0');
            var maxWidth     = ($body.find('[name="max_width"]').val() || '0');
            var cylDiameter  = ($body.find('[name="cyl_diameter"]').val() || '84');
            var accent       = ($body.find('[name="accent"]').val() || 'none');
            var accentText   = ($body.find('[name="accent_text"]').val() || '');
            var customLines  = ($body.find('[name="custom_lines"]').val() || '[]');
            var scrollExit   = ($body.find('[name="scroll_exit"]').val() || 'off');
            var leadScreen   = $body.find('[name="lead_screen"]').is(':checked') ? '1' : '0';
            var cycle        = $body.find('[name="cycle"]').is(':checked') ? '1' : '0';
            var heightMode   = ($body.find('[name="height_mode"]').val() || 'auto');
            var fitContainer = (heightMode === 'fit');
            var autoHeight   = (heightMode === 'auto') && composition !== 'cylinder';
            
            var grows        = (heightMode !== 'auto' && heightMode !== 'fit') && composition !== 'cylinder';
            var engineAuto   = autoHeight || grows;
            var align        = ($body.find('[name="align"]').val()      || 'center');
            var fill         = ($body.find('[name="fill"]').val()       || 'solid');
            var gradMode     = ($body.find('[name="grad_mode"]').val()  || 'travel');
            var gradScope    = ($body.find('[name="grad_scope"]').val() || 'line');
            var gradC1       = ($body.find('[name="grad_c1"]').val()    || '#ff2d55');
            var gradC2       = ($body.find('[name="grad_c2"]').val()    || '#5e5cff');
            block.setAttribute('data-composition',  composition);
            block.setAttribute('data-text',         encodeURIComponent(text));
            block.setAttribute('data-color',        color);
            block.setAttribute('data-loop',         loop);
            block.setAttribute('data-speed',        speed);
            block.setAttribute('data-intensity',    intensity);
            block.setAttribute('data-custom-mode',  customMode);
            block.setAttribute('data-tier',         tier);
            block.setAttribute('data-line-gap',     lineGap);
            block.setAttribute('data-max-width',    maxWidth);
            block.setAttribute('data-cyl-diameter', cylDiameter);
            block.setAttribute('data-accent',       accent);
            block.setAttribute('data-accent-text',  encodeURIComponent(accentText));
            block.setAttribute('data-custom-lines', encodeURIComponent(customLines));
            block.setAttribute('data-scroll-exit',  scrollExit);
            block.setAttribute('data-lead-screen',  leadScreen);
            block.setAttribute('data-cycle',        cycle);
            block.setAttribute('data-height-auto',  engineAuto ? '1' : '0');
            block.setAttribute('data-align',        align);
            block.setAttribute('data-fill',         fill);
            block.setAttribute('data-grad-mode',    gradMode);
            block.setAttribute('data-grad-scope',   gradScope);
            block.setAttribute('data-grad-c1',      gradC1);
            block.setAttribute('data-grad-c2',      gradC2);
            if (engineAuto) {
                
                block.style.height        = 'auto';
                block.style.minHeight     = '0';
                block.style.overflow      = 'visible';
                block.style.flexDirection = 'column';
            } else if (fitContainer) {
                block.style.height        = '100%';
                block.style.minHeight     = '80px';
                block.style.overflow      = 'hidden';
                block.style.flexDirection = '';
            } else {
                
                block.style.minHeight     = '';
                block.style.overflow      = 'hidden';
                block.style.flexDirection = '';
                if (!isNaN(height) && height > 0) block.style.height = height + 'px';
            }
            if (ifr.contentWindow.ImpulseKinetic && ifr.contentWindow.ImpulseKinetic.initEl) {
                ifr.contentWindow.ImpulseKinetic.initEl(block);
            }
        }

        function _impulseKineticSerializeCustomLines() {
            var $body = $('#impulse-settings-body');
            var rows = $body.find('.impulse-kinetic-custom-row');
            var lines = [];
            rows.each(function() {
                var $r = $(this);
                var txt = ($r.find('.impulse-kinetic-custom-text').val() || '').trim();
                var mot = ($r.find('.impulse-kinetic-custom-motion').val() || 'rise');
                var entry = { text: txt, motion: mot };
                var scl = parseFloat($r.find('.impulse-kinetic-line-scale').val());
                if (isFinite(scl) && scl > 0 && Math.abs(scl - 1) > 0.02) entry.scale = scl; 
                var pxv = parseFloat($r.find('.impulse-kinetic-line-px').val());
                if (isFinite(pxv) && pxv > 0) entry.px = Math.round(pxv); 
                var fontv = $r.find('.impulse-kinetic-custom-font').val() || '';
                if (fontv) entry.font = fontv;
                var wtv = $r.find('.impulse-kinetic-custom-weight').val() || '';
                if (wtv) entry.weight = wtv;
                var tgtv = $r.find('.impulse-kinetic-line-target').val() || 'word';
                if (tgtv === 'line') entry.target = 'line'; 
                var colv = ($r.find('.impulse-kinetic-cl-color .impulse-color-text').val() || '').trim();
                if (colv) entry.color = colv;                       
                lines.push(entry);
            });
            $body.find('input[name="custom_lines"]').val(JSON.stringify(lines));
            return lines;
        }

        $(document).on('change input',
            '#impulse-settings-body textarea[name="text"], ' +
            '#impulse-settings-body input[name="color"], ' +
            '#impulse-settings-body input[name="loop"], ' +
            '#impulse-settings-body input[name="cycle"], ' +
            '#impulse-settings-body input[name="lead_screen"], ' +
            '#impulse-settings-body input[name="height_auto"], ' +
            '#impulse-settings-body input[name="fit_container"], ' +
            '#impulse-settings-body input[name="speed"], ' +
            '#impulse-settings-body input[name="intensity"], ' +
            '#impulse-settings-body input[name="line_gap"], ' +
            '#impulse-settings-body input[name="max_width"], ' +
            '#impulse-settings-body input[name="cyl_diameter"], ' +
            '#impulse-settings-body input[name="height"], ' +
            '#impulse-settings-body input[name="grad_c1"], ' +
            '#impulse-settings-body input[name="grad_c2"]',
            function() { setTimeout(function() { _impulseKineticLiveUpdate(); }, 30); }
        );
        
        $(document).on('click', '.impulse-btn-group[data-name="composition"] button', function() {
            var val  = $(this).attr('data-value');
            var desc = $(this).attr('data-desc') || '';
            
            $('.impulse-kinetic-comp-desc').text(desc);

            $(this).closest('.impulse-btn-group').siblings('input[name="composition"]').val(val);
            
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId || !val) return;
            var ifr = document.getElementById('impulse-iframe');
            if (!ifr || !ifr.contentWindow) return;
            var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
            if (!ifrDoc) return;
            var block = ifrDoc.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-kinetic-block');
            if (!block) return;
            block.setAttribute('data-composition', val);
            if (ifr.contentWindow.ImpulseKinetic && ifr.contentWindow.ImpulseKinetic.initEl) {
                try { ifr.contentWindow.ImpulseKinetic.initEl(block); } catch (e) {}
            }
            
            var existingC = $('.impulse-panel-right').data('existing-settings') || {};
            var mergedC = $.extend({}, existingC, { composition: val });
            $('.impulse-panel-right').data('existing-settings', mergedC);
            clearTimeout(window._kCompRebuildT);
            window._kCompRebuildT = setTimeout(function() {
                if (($('.impulse-panel-right').data('element-id')) === elId &&
                    $('.impulse-panel-right').data('element-type') === 'kinetic') {
                    $('#impulse-settings-body').html(buildSettingsForm('kinetic', mergedC, []));
                }
            }, 120);
        });

        $(document).on('click', '.impulse-btn-group[data-name="tier_toggle"] button', function() {
            var val = $(this).attr('data-value');
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId || !val) return;
            $(this).closest('.impulse-btn-group').find('button').removeClass('active');
            $(this).addClass('active');
            $('#impulse-settings-body').find('input[name="tier"]').val(val);
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var merged = $.extend({}, existing, { tier: val });
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') enqueueSave(elId, merged, function() {});
            _impulseKineticLiveUpdate(elId);
        });

        $(document).on('click', '.impulse-btn-group[data-name="accent_toggle"] button', function() {
            var val = $(this).attr('data-value');
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId || !val) return;
            $(this).closest('.impulse-btn-group').find('button').removeClass('active');
            $(this).addClass('active');
            $('#impulse-settings-body').find('input[name="accent"]').val(val);
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var merged = $.extend({}, existing, { accent: val });
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') enqueueSave(elId, merged, function() {});
            _impulseKineticLiveUpdate(elId);
        });

        $(document).on('click', '.impulse-btn-group[data-name="fill"] button', function() {
            var val = $(this).attr('data-value');
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId || !val) return;
            $(this).closest('.impulse-btn-group').find('button').removeClass('active');
            $(this).addClass('active');
            $('#impulse-settings-body').find('input[name="fill"]').val(val);
            var _isGrad = (val === 'gradient');
            $('#impulse-settings-body .impulse-kinetic-grad-swatches').css('display', _isGrad ? 'flex' : 'none');
            $('#impulse-settings-body .impulse-kinetic-grad-opts').css('display', _isGrad ? 'flex' : 'none');
            $('#impulse-settings-body .impulse-kinetic-solid-color').css('display', _isGrad ? 'none' : 'flex');
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var merged = $.extend({}, existing, { fill: val });
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') enqueueSave(elId, merged, function() {});
            _impulseKineticLiveUpdate(elId);
        });

        $(document).on('click', '.impulse-btn-group[data-name="grad_mode"] button, .impulse-btn-group[data-name="grad_scope"] button', function() {
            var $g  = $(this).closest('.impulse-btn-group');
            var nm  = $g.attr('data-name');
            var val = $(this).attr('data-value');
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId || !val) return;
            $g.find('button').removeClass('active');
            $(this).addClass('active');
            $('#impulse-settings-body').find('input[name="' + nm + '"]').val(val);
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var patch = {}; patch[nm] = val;
            var merged = $.extend({}, existing, patch);
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') enqueueSave(elId, merged, function() {});
            _impulseKineticLiveUpdate(elId);
        });

        $(document).on('click', '.impulse-btn-group[data-name="height_mode"] button', function() {
            var val  = $(this).attr('data-value');
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId || !val) return;
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var merged   = $.extend({}, existing, { height_mode: val });
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') enqueueSave(elId, merged, function() {});
            $('#impulse-settings-body').html(buildSettingsForm('kinetic', merged, []));
            setTimeout(function() { _impulseKineticLiveUpdate(elId); }, 30);
        });

        $(document).on('click', '.impulse-btn-group[data-name="align"] button', function() {
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
        });

        $(document).on('input', '#impulse-settings-body input[name="accent_text"]', function() {
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
        });

        $(document).on('change', '#impulse-settings-body input[name="_screen_autoplay_on_ui"]', function() {
            var $sec = $('#impulse-settings-body input[name="screen_autoplay_seconds"]');
            if ($(this).is(':checked')) {
                $sec.prop('disabled', false);
                if (!parseFloat($sec.val()) || parseFloat($sec.val()) <= 0) {
                    $sec.val('5');
                }
                $sec.trigger('change');
            } else {
                $sec.prop('disabled', true);
                $sec.val('0').trigger('change');
            }
        });

        $(document).on('click', '.impulse-btn-group[data-name="custom_mode_toggle"] button', function() {
            var newVal = $(this).attr('data-value');
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId) return;
            
            $(this).closest('.impulse-btn-group').find('button').removeClass('active');
            $(this).addClass('active');
            $('#impulse-settings-body').find('input[name="custom_mode"]').val(newVal);

            
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var merged = $.extend({}, existing, { custom_mode: newVal });
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') {
                enqueueSave(elId, merged, function() {});
            }

            setTimeout(function() {
                $('#impulse-settings-body').html(buildSettingsForm('kinetic', merged, []));

                

                if (newVal === '1') {
                    var seeded = _impulseKineticSerializeCustomLines();
                    var merged2 = $.extend({}, merged, {
                        custom_lines: JSON.stringify(seeded || [])
                    });
                    $('.impulse-panel-right').data('existing-settings', merged2);
                    if (typeof enqueueSave === 'function') {
                        enqueueSave(elId, merged2, function() {});
                    }
                }
                _impulseKineticLiveUpdate(elId);
            }, 30);
        });

        $(document).on('input', '.impulse-kinetic-custom-text', function() {
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
        });

        $(document).on('click', '.impulse-kinetic-mo-trigger', function(e) {
            e.stopPropagation();
            var $menu = $(this).siblings('.impulse-kinetic-mo-menu');
            var wasOpen = $menu.is(':visible');
            $('.impulse-kinetic-mo-menu').hide();
            if (!wasOpen) {
                $menu.show();
                var $act = $menu.find('.impulse-kinetic-mo-opt.active');
                if ($act.length) {
                    $menu[0].scrollTop = $act[0].offsetTop - ($menu[0].clientHeight / 2) + ($act[0].offsetHeight / 2);
                }
            }
        });
        $(document).on('click', '.impulse-kinetic-mo-opt', function(e) {
            e.stopPropagation();
            var val = $(this).attr('data-value');
            var label = $(this).text();
            var $wrap = $(this).closest('.impulse-kinetic-mo');
            $wrap.find('.impulse-kinetic-custom-motion').val(val);
            $wrap.find('.impulse-kinetic-mo-label').text(label);
            $wrap.find('.impulse-kinetic-mo-opt').removeClass('active').css('background', 'transparent');
            $(this).addClass('active').css('background', (window.ImpC && window.ImpC.surface) || 'rgba(255,255,255,0.08)');
            $wrap.find('.impulse-kinetic-mo-menu').hide();
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });
        $(document).on('click', function() { $('.impulse-kinetic-mo-menu').hide(); });

        $(document).on('click', '.impulse-kinetic-tgt-toggle', function(e) {
            e.stopPropagation();
            var $inp = $(this).closest('.impulse-kinetic-custom-row').find('.impulse-kinetic-line-target');
            var next = ($inp.val() === 'line') ? 'word' : 'line';
            $inp.val(next);
            $(this).text(next === 'line' ? 'Line' : 'Word');
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });

        $(document).on('change', '.impulse-kinetic-custom-font', function() {
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
        });

        $(document).on('change input', '.impulse-kinetic-cl-color .impulse-color-text', function() {
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-kinetic-wt-trigger', function(e) {
            e.stopPropagation();
            var $menu = $(this).siblings('.impulse-kinetic-wt-menu');
            var wasOpen = $menu.is(':visible');
            $('.impulse-kinetic-wt-menu').hide();
            if (!wasOpen) $menu.show();
        });
        $(document).on('click', '.impulse-kinetic-wt-opt', function(e) {
            e.stopPropagation();
            var val = $(this).attr('data-value');
            var label = $(this).text();
            var $wrap = $(this).closest('.impulse-kinetic-wt');
            $wrap.find('.impulse-kinetic-custom-weight').val(val);
            $wrap.find('.impulse-kinetic-wt-label').text(label);
            $wrap.find('.impulse-kinetic-wt-opt').removeClass('active').css('background', 'transparent');
            $(this).addClass('active').css('background', (window.ImpC && window.ImpC.surface) || 'rgba(255,255,255,0.08)');
            $wrap.find('.impulse-kinetic-wt-menu').hide();
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });
        $(document).on('click', function() { $('.impulse-kinetic-wt-menu').hide(); });

        $(document).on('click', '.impulse-kinetic-size-trigger', function(e) {
            e.stopPropagation();
            var $menu = $(this).siblings('.impulse-kinetic-size-menu');
            var wasOpen = $menu.is(':visible');
            $('.impulse-kinetic-size-menu').hide();
            if (!wasOpen) {
                $menu.show();
                
                var $act = $menu.find('.impulse-kinetic-size-opt.active');
                if ($act.length) {
                    $menu[0].scrollTop = $act[0].offsetTop - ($menu[0].clientHeight / 2) + ($act[0].offsetHeight / 2);
                }
            }
        });
        $(document).on('click', '.impulse-kinetic-size-opt', function(e) {
            e.stopPropagation();
            var val = $(this).attr('data-value');           
            var $wrap = $(this).closest('.impulse-kinetic-size');
            $wrap.find('.impulse-kinetic-line-scale').val(val);
            $wrap.find('.impulse-kinetic-size-label').text($(this).text()); 
            $wrap.find('.impulse-kinetic-size-opt').removeClass('active').css('background', 'transparent');
            $(this).addClass('active').css('background', (window.ImpC && window.ImpC.surface) || 'rgba(255,255,255,0.08)');
            $wrap.find('.impulse-kinetic-size-menu').hide();
            _impulseKineticSerializeCustomLines();
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
            
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });
        $(document).on('click', function() { $('.impulse-kinetic-size-menu').hide(); });

        $(document).on('input change', '.impulse-kinetic-line-px', function() {
            _impulseKineticSerializeCustomLines();
            clearTimeout(window._kPxT);
            window._kPxT = setTimeout(function() {
                _impulseKineticLiveUpdate();
                if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
            }, 220);
        });

        $(document).on('click', '.impulse-scrollexit-btn', function() {
            var val = $(this).attr('data-value');
            var $grp = $(this).closest('.impulse-scrollexit-group');
            $grp.parent().find('input[name="scroll_exit"]').val(val);
            $grp.find('.impulse-scrollexit-btn').removeClass('active');
            $(this).addClass('active');
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
        });
        
        function _numstepApply($inp, dir) {
            var min  = parseFloat($inp.attr('min'));  if (!isFinite(min))  min  = -Infinity;
            var max  = parseFloat($inp.attr('max'));  if (!isFinite(max))  max  = Infinity;
            var step = parseFloat($inp.attr('step')); if (!isFinite(step) || step <= 0) step = 1;
            var cur  = parseFloat($inp.val());
            if (!isFinite(cur)) cur = isFinite(min) ? min : 0;   
            cur += dir * step;
            cur = Math.max(min, Math.min(max, cur));
            cur = Math.round(cur * 1000) / 1000;                 
            $inp.val(cur).trigger('input');
        }
        var _numTimer = null, _numInp = null;
        function _numStop() {
            if (_numTimer) { clearTimeout(_numTimer); _numTimer = null; }
            if (_numInp) { _numInp.trigger('change'); _numInp = null; }   
        }
        $(document).on('mousedown touchstart', '.impulse-numstep-up, .impulse-numstep-down', function(e) {
            e.preventDefault();
            var $inp = $(this).closest('.impulse-numstep').find('.impulse-numstep-input');
            if (!$inp.length) return;
            var dir = $(this).hasClass('impulse-numstep-up') ? 1 : -1;
            _numStop();
            _numInp = $inp;
            _numstepApply($inp, dir);                
            var delay = 130;
            _numTimer = setTimeout(function tick() {  
                _numstepApply($inp, dir);
                delay = Math.max(35, delay - 10);
                _numTimer = setTimeout(tick, delay);
            }, 380);
        });
        $(document).on('mouseup mouseleave touchend touchcancel', function() { _numStop(); });

        function impulseUpgradeNumberInputs(root) {
            root = root || document;
            if (!root.querySelectorAll) return;
            var sel = 'input[type="number"]:not(.impulse-numstep-input),'
                    + 'input[type="text"][inputmode="numeric"]:not(.impulse-numstep-input),'
                    + 'input[type="text"][inputmode="decimal"]:not(.impulse-numstep-input)';
            [].forEach.call(root.querySelectorAll(sel), function (inp) {
                if (inp.closest('.impulse-numstep')) return;          
                if (inp.getAttribute('data-no-number') === '1') return; 
                if (inp.type === 'text') {
                    var v = (inp.value || '').trim();
                    if (v !== '' && !/^-?\d*\.?\d+$/.test(v)) return;   
                    var dec = inp.getAttribute('inputmode') === 'decimal';
                    try { inp.type = 'number'; } catch (e) { return; }
                    if (!inp.getAttribute('step')) inp.setAttribute('step', dec ? 'any' : '1');
                }
                inp.classList.add('impulse-numstep-input');
                
                var _explicitW = parseFloat(inp.style.width);
                var _compactW = (isFinite(_explicitW) && _explicitW > 0 && _explicitW <= 96) ? Math.round(_explicitW) : 56;
                var wrap = document.createElement('span');
                wrap.className = 'impulse-numstep impulse-numstep-auto';
                wrap.style.cssText = 'position:relative;display:inline-flex;vertical-align:middle;flex:0 0 auto;width:' + _compactW + 'px';
                inp.parentNode.insertBefore(wrap, inp);
                wrap.appendChild(inp);
                inp.style.flex = '';
                inp.style.width = '100%';
                inp.style.minWidth = '0';
                inp.style.height = '26px';   
                inp.style.paddingRight = '15px';
                inp.style.boxSizing = 'border-box';
                var arrows = document.createElement('span');
                arrows.className = 'impulse-numstep-arrows';
                arrows.innerHTML = '<button type="button" class="impulse-numstep-up" tabindex="-1"><svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5"><path d="M5 15l7-7 7 7"/></svg></button>'
                                 + '<button type="button" class="impulse-numstep-down" tabindex="-1"><svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5"><path d="M5 9l7 7 7-7"/></svg></button>';
                wrap.appendChild(arrows);
            });
        }
        window.impulseUpgradeNumberInputs = impulseUpgradeNumberInputs;
        impulseUpgradeNumberInputs(document);
        (function () {
            var _nt;
            try {
                var _nmo = new MutationObserver(function (muts) {
                    for (var i = 0; i < muts.length; i++) { if (muts[i].addedNodes && muts[i].addedNodes.length) {
                        clearTimeout(_nt); _nt = setTimeout(function () { impulseUpgradeNumberInputs(document); }, 180);
                        return;
                    } }
                });
                _nmo.observe(document.body, { childList: true, subtree: true });
            } catch (e) {}
        })();

        $(document).on('click', '.impulse-kinetic-custom-add', function() {
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var lines = [];
            try {
                var raw = (existing.custom_lines || '[]');
                lines = (typeof raw === 'string') ? JSON.parse(raw) : raw;
            } catch(e) { lines = []; }
            if (!Array.isArray(lines)) lines = [];
            
            var defaults = ['rise','bounce-slide-split','letter-kick-in','drop'];
            lines.push({ text: '', motion: defaults[lines.length % defaults.length] });
            existing.custom_lines = JSON.stringify(lines);
            $('.impulse-panel-right').data('existing-settings', existing);
            $('#impulse-settings-body').html(buildSettingsForm('kinetic', existing, []));
            var elId = $('.impulse-panel-right').data('element-id');
            if (elId && typeof enqueueSave === 'function') {
                enqueueSave(elId, existing, function() {});
            }
            setTimeout(function() { _impulseKineticLiveUpdate(); }, 30);
        });

        window._impulseKineticLiveUpdate = _impulseKineticLiveUpdate;

        $(document).on('click', '.impulse-img-depth-generate-btn', function() {

            
            if (!Impulse.isStandalone) {
                (window.showToast || function(){})('Depth map generation is not available in this build.', 'error');
                return;
            }
            var imageUrl = ($('input[name="image_src"]').val() || '').trim();
            if (!imageUrl) {
                (window.showToast || function(){})('Select an image first', 'error');
                return;
            }
            var $btn = $(this);
            _depthSpinner($btn);

            var _resetBtn = function() {
                if ($btn && $btn.length) $btn.prop('disabled', false).text('Generate Depth');
            };
            var _fail = function(msg) {
                _resetBtn();
                console.error('[depth]', msg);
                (window.showToast || function(){})(msg, 'error');
            };
            $.ajax({
                url: (Impulse.siteUrl || '') + '/api/depth-map.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    image_url:   imageUrl,
                    license_key: (Impulse && Impulse.licenseKey) || '',
                    nonce:       (Impulse && Impulse.nonce) || ''
                }),
                timeout: 300000,
                success: function(resp) {
                    if (!resp || !resp.success || !resp.depth_url) {
                        _fail('Depth generation failed: ' + ((resp && resp.error) || 'Unknown error'));
                        return;
                    }
                    fetch(resp.depth_url)
                        .then(function(r) {
                            if (!r.ok) throw new Error('Depth map fetch failed (' + r.status + ')');
                            return r.blob();
                        })
                        .then(function(blob) {
                            var _fd = new FormData();
                            _fd.append('action', 'instinctor_save_depth_map');
                            _fd.append('nonce', window.Impulse.adminNonce);
                            _fd.append('source_url', imageUrl);
                            _fd.append('file', blob, 'depth-map.png');
                            return $.ajax({ url: ajaxurl, method: 'POST', data: _fd, processData: false, contentType: false });
                        })
                        .then(function(ur) {
                            var depthUrl = ur && ur.success && ur.data && ur.data.url ? ur.data.url : resp.depth_url;
                            $('input[name="depth_map"]').val(depthUrl);
                            var _ifrEl = document.getElementById('impulse-iframe');
                            if (_ifrEl && _ifrEl.contentWindow && _ifrEl.contentWindow.ImpulseDepthParallax) {
                                var _ifrDoc = _ifrEl.contentDocument || _ifrEl.contentWindow.document;
                                var _elId = $('.impulse-panel-right').data('element-id');
                                var _wrapper = _elId && _ifrDoc ? (_ifrDoc.getElementById('img-' + _elId) || _ifrDoc.querySelector('.impulse-el[data-id="' + _elId + '"] .impulse-image-wrapper')) : null;
                                if (_wrapper) {
                                    _wrapper.setAttribute('data-depth-image',    imageUrl);
                                    _wrapper.setAttribute('data-depth-map',      depthUrl);
                                    _wrapper.setAttribute('data-depth-strength', $('input[name="depth_strength"]').val() || '50');
                                    _ifrEl.contentWindow.ImpulseDepthParallax.destroy(_wrapper);
                                    _ifrEl.contentWindow.ImpulseDepthParallax.init(_wrapper);
                                }
                            }
                            _resetBtn();
                            (window.showToast || function(){})('Depth map generated', 'success');
                            autoSaveAndPreview();
                            setTimeout(_rebuildImgPanel, 50);
                        })
                        .catch(function(err) {
                            _fail('Depth map processing failed: ' + (err && err.message ? err.message : 'unknown'));
                        });
                },
                error: function(xhr, status, err) {
                    console.error('[depth] ajax error', status, err, xhr && xhr.status, xhr && xhr.responseText);
                    var _msg;
                    if (xhr && xhr.status === 403)      _msg = 'Depth service: not authenticated — re-login and retry';
                    else if (xhr && xhr.status === 404) _msg = 'Depth service not available in this build (requires standalone backend)';
                    else if (xhr && xhr.status)         _msg = 'Depth service error ' + xhr.status;
                    else                                _msg = 'Depth service unavailable. Please try again.';
                    _fail(_msg);
                }
            });
        });

        $(document).on('input', 'input[name="depth_strength"]', function() {
            var _ifrEl = document.getElementById('impulse-iframe');
            if (!_ifrEl || !_ifrEl.contentWindow || !_ifrEl.contentWindow.ImpulseDepthParallax) return;
            var _elId = $('.impulse-panel-right').data('element-id');
            var _ifrDoc = _ifrEl.contentDocument || _ifrEl.contentWindow.document;
            var _wrapper = _elId && _ifrDoc ? (_ifrDoc.getElementById('img-' + _elId) || _ifrDoc.querySelector('.impulse-el[data-id="' + _elId + '"] .impulse-image-wrapper')) : null;
            if (!_wrapper) return;
            var inst = _ifrEl.contentWindow.ImpulseDepthParallax.instances;
            var id = _wrapper.id;
            if (inst && inst[id] && inst[id].gl) {
                var loc = inst[id].gl.getUniformLocation(inst[id].prog, 'u_strength');
                if (loc) inst[id].gl.uniform1f(loc, parseInt($(this).val()) / 100);
            }
        });

        
        
        (function() {
            var _dpIframe = document.getElementById('impulse-iframe');
            document.addEventListener('mousemove', function(e) {
                if (!_dpIframe || !_dpIframe.contentWindow) return;
                var rect = _dpIframe.getBoundingClientRect();
                var x = (e.clientX - rect.left) / (rect.width  || 1);
                var y = (e.clientY - rect.top)  / (rect.height || 1);
                _dpIframe.contentWindow.postMessage({ type: 'impulse-depth-mouse', x: x, y: y }, '*');
            }, { passive: true });
        })();

        
        
        $(document).on('click', '.impulse-btn-group-visibility button', function() {
            var $btn   = $(this);
            var $group = $btn.closest('.impulse-btn-group-visibility');
            var value  = $btn.data('value');
            var device = currentDevice || 'desktop';

            $group.find('button').removeClass('active');
            $btn.addClass('active');

            var key = device === 'desktop' ? 'visibility' : 'visibility_' + device;
            $group.find('input[type="hidden"]').attr('name', key).val(value);

            var $row = $group.closest('.impulse-setting-row');
            if (device !== 'desktop') { $row.addClass('has-override'); }
            else { $row.removeClass('has-override'); }

            var id = $('.impulse-panel-right').data('element-id');
            if (id) { postToIframe({ type: 'impulse-visibility-update', id: id, device: device, hidden: value === 'off' }); }

            autoSaveAndPreview(true);
        });

        
        $(document).on('click', '.impulse-img-focal-btn', function() {
            var pos = $(this).attr('data-pos');
            var $grid = $(this).closest('#impulse-image-focal');
            $grid.find('.impulse-img-focal-btn').each(function(){ this.style.background = (this.getAttribute('data-pos') === pos) ? ImpC.text : ImpC.panel; });
            $grid.find('input[name="focal_point"]').val(pos).trigger('change');
        });

        $(document).on('click', '#impulse-select-image', function() {
            var currentId = $('input[name="image_id"]').val() || null;
            var fillContainer = $('input[name="fill_container"]').is(':checked');
            var currentFocalPoint = $('input[name="focal_point"]').val() || '50% 50%';
            openImglibPicker({ label: 'Select Image', currentId: currentId, currentFocalPoint: currentFocalPoint, noFocal: !fillContainer }, function(attachment) {
                $('input[name="image_id"]').val(attachment.id);
                $('input[name="image_src"]').val(attachment.url);
                $('input[name="depth_map"]').val(''); 
                if (attachment.focal_point) $('input[name="focal_point"]').val(attachment.focal_point);
                $('.impulse-clear-image-btn').css({'opacity': '1', 'pointer-events': 'auto'});
                var id = $('.impulse-panel-right').data('element-id');
                if (id) {
                    var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                    var settings = collectSettingsFromPanel(existingSettings);
                    var mergedSettings = $.extend({}, existingSettings, settings);
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                        success: function() {
                            $('.impulse-panel-right').data('existing-settings', mergedSettings);
                            refreshPreview();
                            
                            var html = buildSettingsForm('image', mergedSettings, []);
                            $('#impulse-settings-body').html(html);
                        }
                    });
                }
            });
        });

        $(document).on('click', '.impulse-clear-image-btn', function() {
            var $btn = $(this);
            if ($btn.css('pointer-events') === 'none') return;

            $('input[name="image_id"]').val('');

            $btn.css({'opacity': '0.4', 'pointer-events': 'none'});

            var id = $('.impulse-panel-right').data('element-id');
            if (id) {
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var settings = collectSettingsFromPanel(existingSettings);
                settings.image_id = '';
                var mergedSettings = $.extend({}, existingSettings, settings);
                
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                    success: function() {
                        $('.impulse-panel-right').data('existing-settings', mergedSettings);
                        refreshPreview();
                    }
                });
            }
        });

        
        
        $(document).on('click', '#impulse-select-image-popup', function() {
            var currentId = parseInt($('input[name="image_id"]').val(), 10) || null;
            openImglibPicker({ label: 'Select Image', currentId: currentId, noFocal: true }, function(attachment) {
                $('input[name="image_id"]').val(attachment.id);
                $('input[name="src"]').val(attachment.url);
                $('input[name="alt"]').val(attachment.alt || $('input[name="alt"]').val());
                $('.impulse-clear-image-popup-btn').css({'opacity':'1','pointer-events':'auto'});
                var id = $('.impulse-panel-right').data('element-id');
                if (id) {
                    var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                    var settings = collectSettingsFromPanel(existingSettings);
                    var mergedSettings = $.extend({}, existingSettings, settings);
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                        success: function() {
                            $('.impulse-panel-right').data('existing-settings', mergedSettings);
                            refreshPreview();
                        }
                    });
                }
            });
        });

        $(document).on('click', '.impulse-clear-image-popup-btn', function() {
            var $btn = $(this);
            if ($btn.css('pointer-events') === 'none') return;
            $('input[name="image_id"]').val('');
            $('input[name="src"]').val('');
            $btn.css({'opacity':'0.4','pointer-events':'none'});
            var id = $('.impulse-panel-right').data('element-id');
            if (id) {
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var settings = collectSettingsFromPanel(existingSettings);
                settings.image_id = '';
                settings.src = '';
                var mergedSettings = $.extend({}, existingSettings, settings);
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                    success: function() {
                        $('.impulse-panel-right').data('existing-settings', mergedSettings);
                        refreshPreview();
                    }
                });
            }
        });

        $(document).on('click', '#impulse-select-poster', function() {
            openImglibPicker({ label: 'Select Poster Image' }, function(attachment) {
                var url = attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;
                $('input[name="poster_id"]').val(attachment.id).trigger('change');
                $('input[name="poster_url"]').val(url);
                $('#impulse-poster-preview img').attr('src', url);
                $('#impulse-poster-preview').show();
                $('#impulse-select-poster').hide();
                autoSaveAndPreview();
            });
        });

        $(document).on('click', '#impulse-remove-poster', function() {
            $('input[name="poster_id"]').val('').trigger('change');
            $('input[name="poster_url"]').val('');
            $('#impulse-poster-preview').hide();
            $('#impulse-select-poster').show();
            autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-remove-video-file', function() {
            $('input[name="video_file_url"]').val('').trigger('change');
            $('.impulse-video-file-row').hide();
            $('.impulse-video-url-row').show();
            autoSaveAndPreview();
        });

        
        var selectedProducts = [];
        var productModalMode = 'multi'; 
        
        function openProductModal(mode) {
            productModalMode = mode || 'multi';
            selectedProducts = [];

            if (productModalMode === 'single') {
                var pid = $('input[name="product_id"]').val();
                if (pid) selectedProducts = [{id: parseInt(pid), name: 'Product ' + pid}];
                $('#impulse-selected-products').hide();
            } else {
                var existingIds = $('input[name="product_ids"]').val();
                if (existingIds) {
                    String(existingIds).split(',').filter(function(id) { return id; }).forEach(function(id) {
                        selectedProducts.push({id: parseInt(id), name: 'Product ' + id});
                    });
                }
                $('#impulse-selected-products').show();
            }
            
            updateSelectedProducts();
            
            $('#impulse-product-search').val('');
            $('#impulse-product-category').val('');
            loadProducts();
            
            $('#impulse-product-list').removeClass('view-list');
            $('.impulse-product-view-toggle button').removeClass('active');
            $('.impulse-product-view-toggle button[data-view="card"]').addClass('active');
            $('#impulse-product-modal').show();
        }

        $(document).on('click', '#impulse-select-products', function() {
            openProductModal('multi');
        });

        $(document).on('click', '#impulse-select-product', function() {
            openProductModal('single');
        });
        
        function loadProducts(search, category) {
            $('#impulse-product-list').html('<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa">Loading products...</div>');
            $.get(Impulse.api + 'products', {
                search: search || '',
                category: category || '',
                per_page: 50,
                status: 'published',
                _wpnonce: Impulse.nonce
            }, function(response) {
                var products = response.data || response || [];
                if (!Array.isArray(products)) products = [];
                var html = '';
                if (products.length === 0) {
                    html = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa">No products found. Create products in Instinctor &gt; Products first.</div>';
                } else {
                    var selectedIds = selectedProducts.map(function(p) { return p.id; });
                    products.forEach(function(p) {
                        var img = p.image_url || '';
                        var isSelected = selectedIds.indexOf(p.id) !== -1;
                        html += '<div class="impulse-product-item' + (isSelected ? ' selected' : '') + '" data-id="' + p.id + '">';
                        html += '<div class="impulse-product-item-image">';
                        if (img) {
                            html += '<img src="' + img + '" alt="" onerror="this.style.display=\'none\';this.parentNode.innerHTML=\'<span style=color:#666;font-size:9px>No image</span>\'">';
                        } else {
                            html += '<span style="color:#666;font-size:9px">No img</span>';
                        }
                        html += '</div>';
                        html += '<div class="impulse-product-item-info">';
                        html += '<span class="impulse-product-item-name">' + (p.name || 'Untitled') + '</span>';
                        html += '</div>';
                        html += '</div>';
                    });
                }
                $('#impulse-product-list').html(html);
                
                var $modalContent = $('#impulse-product-modal .impulse-modal-content');
                if (products.length >= 20) {
                    $modalContent.removeClass('impulse-modal-lg').addClass('impulse-modal-xl');
                } else {
                    $modalContent.removeClass('impulse-modal-xl').addClass('impulse-modal-lg');
                }
            }).fail(function() {
                $('#impulse-product-list').html('<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa">Error loading products. Please try again.</div>');
            });
        }

        var productSearchTimer;
        $(document).on('input', '#impulse-product-search', function() {
            clearTimeout(productSearchTimer);
            var search = $(this).val();
            var category = $('#impulse-product-category').val();
            productSearchTimer = setTimeout(function() {
                loadProducts(search, category);
            }, 300);
        });
        
        $(document).on('change', '#impulse-product-category', function() {
            var search = $('#impulse-product-search').val();
            var category = $(this).val();
            loadProducts(search, category);
        });

        $(document).on('click', '.impulse-product-view-toggle button', function() {
            var view = $(this).data('view');
            $(this).addClass('active').siblings().removeClass('active');
            if (view === 'list') {
                $('#impulse-product-list').addClass('view-list');
            } else {
                $('#impulse-product-list').removeClass('view-list');
            }
        });

        $(document).on('click', '.impulse-product-item', function() {
            var id = $(this).data('id');
            var name = $(this).find('.impulse-product-item-name').text();
            
            if (productModalMode === 'single') {
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    selectedProducts = [];
                } else {
                    $('.impulse-product-item').removeClass('selected');
                    $(this).addClass('selected');
                    selectedProducts = [{ id: id, name: name }];
                }
            } else {
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    selectedProducts = selectedProducts.filter(function(p) { return p.id !== id; });
                } else {
                    $(this).addClass('selected');
                    selectedProducts.push({ id: id, name: name });
                }
            }
            
            updateSelectedProducts();
        });
        
        function updateSelectedProducts() {
            var html = '';
            selectedProducts.forEach(function(p) {
                html += '<div class="impulse-selected-tag" data-id="' + p.id + '">';
                html += p.name;
                html += '<button type="button"><svg viewBox="0 0 24 24" width="8" height="8" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                html += '</div>';
            });
            $('.impulse-selected-list').html(html);
        }
        
        $(document).on('click', '.impulse-selected-tag button', function() {
            var id = $(this).closest('.impulse-selected-tag').data('id');
            selectedProducts = selectedProducts.filter(function(p) { return p.id !== id; });
            $('.impulse-product-item[data-id="' + id + '"]').removeClass('selected');
            updateSelectedProducts();
        });
        
        $('#impulse-apply-products').on('click', function() {
            
            if (typeof window._productPickerCallback === 'function' && selectedProducts.length) {
                var cb = window._productPickerCallback;
                window._productPickerCallback = null;
                cb(selectedProducts[0].id, selectedProducts[0].name);
                $('#impulse-product-modal').hide();
                return;
            }
            if (productModalMode === 'single') {
                var pid = selectedProducts.length ? selectedProducts[0].id : '';
                var pname = selectedProducts.length ? selectedProducts[0].name : '';
                $('input[name="product_id"]').val(pid);
                $('input[name="product_id"]').nextAll('p').remove();
                if (pid && pname) {
                    $('input[name="product_id"]').after('<p style="margin:6px 0 0;font-size:11px;color:#aaa">Selected: ' + pname + '</p>');
                }
                if (!$('input[name="product_name"]').length) {
                    $('input[name="product_id"]').after('<input type="hidden" name="product_name" value="' + (pname || '') + '">');
                } else {
                    $('input[name="product_name"]').val(pname || '');
                }
            } else {
                var ids = selectedProducts.map(function(p) { return p.id; });
                $('input[name="product_ids"]').val(ids.join(','));
                
                var $chipList = $('.impulse-manual-products-list');
                if ($chipList.length) {
                    var chipsHtml = '';
                    if (ids.length) {
                        selectedProducts.forEach(function(p) {
                            chipsHtml += '<span class="impulse-manual-product-chip" data-id="' + p.id + '" style="display:inline-flex;align-items:center;gap:4px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;padding:2px 6px;font-size:10px;color:'+ImpC.text+'">' + (p.name || ('#' + p.id));
                            chipsHtml += '<span class="impulse-manual-product-remove" title="Remove" style="display:inline-flex;cursor:pointer;flex-shrink:0"><svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></span></span>';
                        });
                    } else {
                        chipsHtml = '<span style="font-size:11px;color:'+ImpC.dim+';padding:2px 0">No products selected</span>';
                    }
                    $chipList.html(chipsHtml);
                }
            }
            $('#impulse-product-modal').hide();
            
            autoSaveAndRefresh();
        });

        
        
        $(document).on('click', '#block-addon-add', function() {
            var addons = getBlockAddons();
            addons.push({name:'', type:'checkbox', price:0, price_type:'flat', required:false, multiline:false, options:[], product_id:null, product_name:''});
            window._blockAddonOpenIdx = addons.length - 1;
            saveBlockAddons(addons);
            rebuildAddonList(addons);
        });

        $(document).on('click', '.block-addon-row-hdr', function(e) {
            if ($(e.target).closest('.block-addon-remove').length) return;
            var i = parseInt($(this).closest('.block-addon-row').data('idx'));
            window._blockAddonOpenIdx = (window._blockAddonOpenIdx === i) ? -1 : i;
            rebuildAddonList(getBlockAddons());
        });

        $(document).on('click', '.block-addon-remove', function(e) {
            e.stopPropagation();
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons.splice(i, 1);
            if (window._blockAddonOpenIdx >= addons.length) window._blockAddonOpenIdx = addons.length - 1;
            saveBlockAddons(addons);
            rebuildAddonList(addons);
        });

        $(document).on('input', '.ba-name', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons[i].name = $(this).val();
            saveBlockAddons(addons);
            $(this).closest('.block-addon-row').find('.ba-row-label').text(addons[i].name || 'Untitled field');
        });

        $(document).on('click', '.ba-type', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons[i].type = $(this).data('type');
            window._blockAddonOpenIdx = i;
            saveBlockAddons(addons);
            rebuildAddonList(addons);
        });

        $(document).on('input', '.ba-price', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons[i].price = parseFloat($(this).val()) || 0;
            saveBlockAddons(addons);
        });

        $(document).on('click', '.ba-ptype', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons[i].price_type = $(this).data('ptype');
            $(this).siblings('.ba-ptype').removeClass('active'); $(this).addClass('active');
            saveBlockAddons(addons);
        });

        $(document).on('change', '.ba-required', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons[i].required = $(this).is(':checked');
            saveBlockAddons(addons);
        });

        $(document).on('change', '.ba-multiline', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            addons[i].multiline = $(this).is(':checked');
            saveBlockAddons(addons);
        });

        $(document).on('click', '.ba-option-add', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            if (!Array.isArray(addons[i].options)) addons[i].options = [];
            addons[i].options.push('');
            window._blockAddonOpenIdx = i;
            saveBlockAddons(addons);
            rebuildAddonList(addons);
            $(document).find('.ba-options-list[data-idx="' + i + '"] .ba-option-val').last().focus();
        });

        $(document).on('click', '.ba-option-remove', function() {
            var $list = $(this).closest('.ba-options-list');
            var i = parseInt($list.data('idx'));
            var oi = $(this).closest('.ba-option-row').index();
            var addons = getBlockAddons();
            addons[i].options.splice(oi, 1);
            window._blockAddonOpenIdx = i;
            saveBlockAddons(addons);
            rebuildAddonList(addons);
        });

        $(document).on('input', '.ba-option-val', function() {
            var $list = $(this).closest('.ba-options-list');
            var i = parseInt($list.data('idx'));
            var addons = getBlockAddons();
            var opts = [];
            $list.find('.ba-option-val').each(function() { opts.push($(this).val()); });
            addons[i].options = opts;
            saveBlockAddons(addons);
        });

        $(document).on('click', '.ba-scope', function() {
            var i = parseInt($(this).data('idx'));
            var scope = $(this).data('scope');
            var addons = getBlockAddons();
            if (scope === 'all') {
                addons[i].product_id = null;
                addons[i].product_name = '';
                window._blockAddonOpenIdx = i;
                saveBlockAddons(addons);
                rebuildAddonList(addons);
            } else {
                window._productPickerCallback = function(pid, pname) {
                    addons[i].product_id = pid;
                    addons[i].product_name = pname;
                    window._blockAddonOpenIdx = i;
                    saveBlockAddons(addons);
                    rebuildAddonList(addons);
                };
                openProductModal('single');
            }
        });

        $(document).on('click', '.ba-scope-pick', function() {
            var i = parseInt($(this).data('idx'));
            var addons = getBlockAddons();
            window._productPickerCallback = function(pid, pname) {
                addons[i].product_id = pid;
                addons[i].product_name = pname;
                window._blockAddonOpenIdx = i;
                saveBlockAddons(addons);
                rebuildAddonList(addons);
            };
            openProductModal('single');
        });

        $(document).on('click', '.impulse-btn-group[data-name="source"] button', function() {
            var source = $(this).data('value');
            if (source === 'query') {
                $('.impulse-products-manual').hide();
                $('.impulse-products-query').show();
                $('.impulse-products-count-wrapper').show();
                $('.impulse-radius-only-row').hide();
            } else {
                $('.impulse-products-manual').show();
                $('.impulse-products-query').hide();
                $('.impulse-products-count-wrapper').hide();
                $('.impulse-radius-only-row').show();
            }
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-ppc-collapsible-hdr', function() {
            var body = $(this).siblings('.impulse-ppc-collapsible-body');
            var chv  = $(this).find('.impulse-ppc-chevron');
            var open = body.is(':visible');
            body.toggle(!open);
            chv.css('transform', open ? 'rotate(-90deg)' : 'rotate(0deg)');
        });

        
        $(document).on('input', '#impulse-bug-text', function() {
            var el = this;
            el.style.height = '26px';
            el.style.height = Math.min(el.scrollHeight, 88) + 'px';
            $('#impulse-bug-submit').toggle($(this).val().trim().length > 0);
        });

        $(document).on('click', '#impulse-bug-submit', function() {
            var $btn = $(this);
            var text = $('#impulse-bug-text').val().trim();
            if (!text) { window.showToast('Please describe the bug first.', 'error'); return; }
            $btn.prop('disabled', true).text('Sending…');
            $.post(ajaxurl, {
                action: 'instinctor_submit_ticket',
                nonce: Impulse.adminNonce,
                subject: 'Editor bug report',
                body: text + '\n\n[Page: ' + (Impulse.pageId || 'none') + '][v' + (typeof INSTINCTOR_VERSION !== 'undefined' ? INSTINCTOR_VERSION : '') + ']',
                type: 'bug',
                email: Impulse.userEmail || Impulse.licenseEmail || ''
            }, function(resp) {
                $btn.prop('disabled', false).text('Send');
                if (resp.success) {
                    $('#impulse-bug-text').val('');
                    $('#impulse-bug-submit').hide();
                    window.showToast('Bug reported — thank you!', 'success');
                } else {
                    window.showToast('Could not send report.', 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false).text('Send');
                window.showToast('Request failed.', 'error');
            });
        });

        
        $(document).on('click', '.impulse-account-preview-toggle', function() {
            var $btn = $(this);
            var $input = $btn.next('input[name="preview_loggedout"]');
            var nowOut = $input.val() !== '1';
            $input.val(nowOut ? '1' : '');
            $btn.text(nowOut ? 'Viewing: Logged Out' : 'View as Logged Out');
            $btn.css({ background: nowOut ? ''+ImpC.white+'' : ''+ImpC.panel+'', color: nowOut ? ''+ImpC.surface2+'' : ''+ImpC.muted+'', borderColor: nowOut ? '#888' : ''+ImpC.border+'' });
            var cached = $('.impulse-panel-right').data('existing-settings') || {};
            cached.preview_loggedout = nowOut;
            $('.impulse-panel-right').data('existing-settings', cached);
            autoSaveAndPreview(true);
        });

        $(document).on('click', '#ppc-modal-toggle-btn', function() {
            var $btn  = $(this);
            var $val  = $('#ppc-modal-val');
            var $body = $('#ppc-modal-body');
            var now   = $val.val() !== '1';
            $val.val(now ? '1' : '');
            $btn.text('PRODUCT CARD ' + (now ? 'ON' : 'OFF'));
            $btn.css({ background: now ? ''+ImpC.white+'' : ''+ImpC.panel+'', color: now ? ''+ImpC.surface2+'' : ''+ImpC.dim+'' });
            $body.toggle(now);
            
            var cached = $('.impulse-panel-right').data('existing-settings') || {};
            cached.enable_modal = now;
            $('.impulse-panel-right').data('existing-settings', cached);
            
            if (now) {
                window._impulseQvPreviewElementId = null;
                postToIframe({ type: 'impulse-quickview-preview-open' });
            } else {
                postToIframe({ type: 'impulse-quickview-preview-close' });
            }
            autoSaveAndPreview(true);
        });

        $(document).on('click', '.impulse-panel-right [data-name="display_mode"] button[data-value]', function() {
            var v = $(this).data('value');
            var $p = $(this).closest('.impulse-panel-right');
            var toggle = function(id, show) { var el = document.getElementById(id); if (el) el.style.display = show ? '' : 'none'; };
            toggle('ppc-carousel-section', v === 'carousel');
            toggle('ppc-single-section',   v === 'single');
            toggle('ppc-maxcards-row',      v === 'carousel');
            toggle('ppc-fadeflip-row',      v === 'single');
            toggle('ppc-slidescroll-row',   v === 'carousel');
            var $gc = $p.find('.impulse-products-query .impulse-inline-right');
            $gc.toggle(v === 'grid');
        });

        $(document).on('click', '.impulse-pcard-toggle', function() {
            var $btn   = $(this);
            var field  = $btn.data('field');
            var onVal  = $btn.data('on');
            var offVal = $btn.data('off');
            var isOn   = $btn.hasClass('active');
            var nowOn  = !isOn;
            $btn.toggleClass('active', nowOn);
            
            $btn.closest('.impulse-panel-inner, .impulse-settings-panel, form, body')
                .find('input[name="' + field + '"]').first().val(nowOn ? onVal : offVal);
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-btn-group[data-name="carousel_cards"] button', function() {
            if ($(this).data('value') == 1) {
                
                var $dm = $('[data-name="display_mode"]');
                $dm.find('button').removeClass('active');
                $dm.find('button[data-value="single"]').addClass('active');
                $dm.find('input[type="hidden"]').val('single');
                $dm.trigger('click-programmatic', ['single']); 
                
                var evt = new CustomEvent('impulse:display-mode-change', {detail:{v:'single'}});
                document.dispatchEvent(evt);
                
                var cs = document.getElementById('ppc-carousel-section');
                var ss = document.getElementById('ppc-single-section');
                var ff = document.getElementById('ppc-fadeflip-row');
                var ss2 = document.getElementById('ppc-slidescroll-row');
                var mc = document.getElementById('ppc-maxcards-row');
                if (cs) cs.style.display = 'none';
                if (ss) ss.style.display = '';
                if (ff) ff.style.display = '';
                if (ss2) ss2.style.display = 'none';
                if (mc) mc.style.display = 'none';
            }
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-btn-group[data-name="query_type"] button', function() {
            var qt = $(this).data('value');
            $('.impulse-query-category-row').toggle(qt === 'category');
            autoSaveAndRefresh();
        });

        $(document).on('change', 'select[name="category_id"]', function() {
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-manual-product-remove', function() {
            var chip = $(this).closest('.impulse-manual-product-chip');
            var removedId = chip.data('id').toString();
            var $input = chip.closest('.impulse-products-manual').find('input[name="product_ids"]');
            var ids = $input.val().split(',').filter(function(x) { return x.trim() && x.trim() !== removedId; });
            $input.val(ids.join(','));
            chip.remove();
            autoSaveAndRefresh();
        });

        

        
        $(document).on('click', '.impulse-btn-group[data-name="height_mode"] button', function() {
            var mode = $(this).data('value');

            var $row = $('.impulse-slider-height-settings');
            if (mode === 'auto') {
                $row.css({ opacity: '0.45', 'pointer-events': 'none' });
            } else {
                $row.css({ opacity: '', 'pointer-events': '' });
            }
            
            $('.impulse-section-height-vh-wrap').css('display',     mode === 'vh'     ? 'block' : 'none');
            $('.impulse-section-height-aspect-wrap').css('display', mode === 'aspect' ? 'block' : 'none');
            $('.impulse-section-height-px-wrap').css('display',     mode === 'px'     ? 'block' : 'none');

            
            
            if ($('.impulse-section-height-vh-wrap, .impulse-section-height-aspect-wrap, .impulse-section-height-px-wrap').length) {
                autoSaveAndRefresh();
            } else {
                autoSaveAndPreview();
            }
        });

        
        $(document).on('click', '.impulse-btn-group[data-name="aspect_ratio"] button', function() {
            autoSaveAndRefresh();
        });
        
        $(document).on('change', 'input[name="height_px"]', function() {
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-btn-group[data-name="cart_mode"] button', function() {
            var mode = $(this).data('value');
            $('.impulse-cart-mini-settings').toggle(mode === 'mini');
            $('.impulse-cart-full-settings').toggle(mode === 'full');
        });

        $(document).on('click', '.impulse-btn-group[data-name="hover_effect"] button', function() {
            var effect = $(this).data('value');
            if (effect === 'shadow') {
                $('.impulse-hover-shadow-row').show();
            } else {
                $('.impulse-hover-shadow-row').hide();
            }
        });

        var videoMasksCache = null;
        function loadVideoMasks() {
            var $grid = $('.impulse-video-mask-picker');
            if (!$grid.length) return;
            var currentMaskId = parseInt($('input[name="mask_id"]').val() || 0);
            
            function renderMasks(masks) {
                
                $grid.find('.impulse-mask-item:not([data-mask-id="0"])').remove();
                masks.forEach(function(s) {
                    var isActive = s.id === currentMaskId;
                    var svg = s.svg || '';
                    var vb = s.viewbox || '0 0 24 24';
                    var $item = $('<div class="impulse-mask-item' + (isActive ? ' active' : '') + '" data-mask-id="' + s.id + '" style="flex:1 1 0;min-width:0;aspect-ratio:1;background:'+ImpC.panel+';border:1px solid ' + (isActive ? ''+ImpC.text+'' : ''+ImpC.border+'') + ';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:4px;box-sizing:border-box">');
                    $item.append('<svg viewBox="' + vb + '" width="100%" height="100%" fill="'+ImpC.muted+'" stroke="none" style="display:block">' + svg + '</svg>');
                    $item.data('shape-data', s);
                    $grid.append($item);
                });
                $('.impulse-video-masks-loading').remove();
            }
            
            if (videoMasksCache) {
                renderMasks(videoMasksCache);
                return;
            }
            
            $.ajax({
                url: Impulse.shapesApiUrl,
                method: 'GET',
                data: { category: 'masks' },
                dataType: 'json',
                timeout: 10000,
                success: function(data) {
                    videoMasksCache = data.shapes || [];
                    renderMasks(videoMasksCache);
                },
                error: function() {
                    $('.impulse-video-masks-loading').text('Could not load masks');
                }
            });
        }

        $(document).on('click', '.impulse-mask-item', function() {
            var $item = $(this);
            var maskId = parseInt($item.data('mask-id'));
            var wasActive = $item.hasClass('active');

            $('.impulse-mask-item').removeClass('active').css('border-color', ''+ImpC.border+'');
            
            if (wasActive) {
                
                $('input[name="mask_id"]').val('');
                $('input[name="mask_url"]').val('');
                $('input[name="mask_viewbox"]').val('');
                $('.impulse-video-aspect-row').show();
                autoSaveAndRefresh();
                return;
            }
            
            $item.addClass('active').css('border-color', ''+ImpC.white+'');
            
            var shapeData = $item.data('shape-data');
            if (!shapeData) return;

            var vb = shapeData.viewbox || '0 0 24 24';
            var svg = (shapeData.svg || '').replace(/\s*fill="[^"]*"/g,'').replace(/\s*stroke="[^"]*"/g,'');
            
            var svgContent = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="' + vb + '" fill="white" stroke="none">' + svg + '</svg>';
            var maskUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgContent);

            $('input[name="mask_id"]').val(maskId);
            $('input[name="mask_url"]').val(maskUrl);
            $('input[name="mask_viewbox"]').val(vb);
            $('.impulse-video-aspect-row').hide();
            autoSaveAndRefresh();
        });

        

        $(document).on('change', 'input[name="slide_bg_color"]', function() {
            var val = $(this).val();
            var $slidesInput = $('input[name="slides"]');
            if (!$slidesInput.length) return;
            var _sl; try { _sl = JSON.parse($slidesInput.val()); } catch(e) { return; }
            var _ci = parseInt($('input[name="current_slide"]').val()) || 0;
            if (_sl[_ci]) { _sl[_ci].background = val; $slidesInput.val(JSON.stringify(_sl)); }
            autoSaveAndPreview();
        });
        
        $(document).on('impulse-image-selected', function(e, data) {
            if (data && data.field === 'slide_image') {
                var url = data.url || data.src || '';
                $('input[name="slide_image"]').val(url);
                var $slidesInput = $('input[name="slides"]');
                if (!$slidesInput.length) return;
                var _sl; try { _sl = JSON.parse($slidesInput.val()); } catch(e) { return; }
                var _ci = parseInt($('input[name="current_slide"]').val()) || 0;
                if (_sl[_ci]) { _sl[_ci].image_url = url; $slidesInput.val(JSON.stringify(_sl)); }
                autoSaveAndPreview();
            }
        });
        
        $(document).on('click', '.impulse-carousel-add-images', function() {
            openImglibPicker({ label: 'Add Slides from Images', multiple: true }, function(attachments) {
                if (!attachments || !attachments.length) return;
                var $slidesInput = $('input[name="slides"]');
                if (!$slidesInput.length) return;
                var _sl; try { _sl = JSON.parse($slidesInput.val()); } catch(e) { _sl = []; }
                
                _sl = _sl.filter(function(s) { return s.image_url || (s.background && s.background !== ''); });
                attachments.forEach(function(att) {
                    var url = att.url || att.src || (att.sizes && att.sizes.large && att.sizes.large.url) || '';
                    if (url) _sl.push({ id: 'slide-' + _sl.length, image_url: url, background: '', valign: 'center', link: '' });
                });
                if (_sl.length === 0) _sl.push({ id: 'slide-0', background: '', valign: 'center' });
                $slidesInput.val(JSON.stringify(_sl));
                $('input[name="slide_count"]').val(_sl.length);
                $('input[name="current_slide"]').val(0);
                autoSaveAndPreview();
                var _rpId = selectedElementId, _rpType = selectedElementType;
                setTimeout(function() { if (_rpId) openSettings(_rpId, _rpType); }, 400);
            });
        });

        $(document).on('input change', 'input[name="slide_link"]', function() {
            var val = $(this).val();
            var $slidesInput = $('input[name="slides"]');
            if (!$slidesInput.length) return;
            var _sl; try { _sl = JSON.parse($slidesInput.val()); } catch(e) { return; }
            var _ci = parseInt($('input[name="current_slide"]').val()) || 0;
            if (_sl[_ci]) { _sl[_ci].link = val; $slidesInput.val(JSON.stringify(_sl)); }
        });
        $(document).on('blur', 'input[name="slide_link"]', function() { autoSaveAndPreview(); });
        
        $(document).on('click', '.impulse-slide-valign-btn', function() {
            var val = $(this).data('value');
            $(this).closest('[data-target="slide-valign"]').find('.impulse-slide-valign-btn').removeClass('active');
            $(this).addClass('active');
            var $slidesInput = $('input[name="slides"]');
            if (!$slidesInput.length) return;
            var _sl; try { _sl = JSON.parse($slidesInput.val()); } catch(e) { return; }
            var _ci = parseInt($('input[name="current_slide"]').val()) || 0;
            if (_sl[_ci]) { _sl[_ci].valign = val; $slidesInput.val(JSON.stringify(_sl)); }
            autoSaveAndPreview();
        });

        

        
        
        $(document).on('change', '#impulse-screen-bar .impulse-color-text, #impulse-settings-body .impulse-color-text[name^="screen_"]', function() {
            var name = $(this).attr('name') || '';
            var val  = $(this).val() || '';
            if (!name || !val) return;

            

            
            
            $('input[name="' + name + '"]').not(this).val(val);
            var _smActive = Impulse.pageSettings && (true);
            if (!_smActive) return;

            
            var _curEffLU = $('input[name="screen_cloud_effect"]').val() || 'none';

            

            
            
            function _lookup(slot) {
                var perEff = $('input[name="screen_' + _curEffLU + '_color' + slot + '"]').val();
                if (perEff) return perEff;
                
                return $('input[name="screen_3d_color' + slot + '"]').val() || '';
            }
            var _c1 = _lookup(1) || '#000000';
            var _c2 = _lookup(2) || '#333333';
            var _c3 = _lookup(3) || '#666666';
            var _c4 = _lookup(4) || '#cccccc';
            
            var _bgB = $('input[name="screen_' + _curEffLU + '_bg_color"]').val()
                    || $('input[name="bg_color"]').val()
                    || '';
            
            var screenIdx = getActiveScreenIndex();
            if (screenIdx === 0) {
                
                if (window._basePageEnv) window._basePageEnv[name] = val;
                var settings = collectSettingsFromPanel(Impulse.pageSettings || {});
                Impulse.pageSettings = settings;

                

                try {
                    var _ifrDoc2 = document.getElementById('impulse-iframe').contentDocument;
                    var _sw = _ifrDoc2 && _ifrDoc2.querySelector('.impulse-screen-wrapper');
                    if (_sw) {
                        var _attrMap = {
                            screen_3d_color1: '3dColor1', screen_3d_color2: '3dColor2',
                            screen_3d_color3: '3dColor3', screen_3d_color4: '3dColor4'
                        };
                        
                        _attrMap['screen_' + _curEffLU + '_color1'] = '3dColor1';
                        _attrMap['screen_' + _curEffLU + '_color2'] = '3dColor2';
                        _attrMap['screen_' + _curEffLU + '_color3'] = '3dColor3';
                        _attrMap['screen_' + _curEffLU + '_color4'] = '3dColor4';
                        if (_attrMap[name]) _sw.dataset[_attrMap[name]] = val;
                    }
                } catch(e) {}
                saveScreenBarSettings(false);
            } else {
                
                _saveScreenEnvSettings();
            }

            

            try {
                var _ifrm = document.getElementById('impulse-iframe');
                var _3d = _ifrm && _ifrm.contentWindow && _ifrm.contentWindow._impulse3D;
                var _fx = _ifrm && _ifrm.contentWindow && _ifrm.contentWindow._impulseFX;
                if (_3d && _3d.updateColors) _3d.updateColors([_c1, _c2, _c3, _c4]);
                if (_fx && _fx.update) {
                    var _opts = { color1: _c1, color2: _c2 };

                    
                    if (_curEffLU === 'nebula' || _curEffLU === 'flow') {
                        _opts.color3 = _c3;
                        if (_bgB && _bgB.charAt && _bgB.charAt(0) === '#') _opts.bgColor = _bgB;
                    } else {
                        _opts.bgColor = _c3;
                    }
                    _fx.update(_opts);
                }
            } catch(e) {}
        });

        
        
        $(document).on('change', '#impulse-settings-body input[name="image_pin_to_screen"]', function() {
            $('#impulse-image-pin-controls').toggle(!!this.checked);
        });
        $(document).on('click', '#impulse-settings-body .impulse-align-grid[data-name="image_anchor"] .impulse-align-dot', function(e) {
            e.preventDefault();
            var ca = $(this).data('ca'), va = $(this).data('va');
            var sfx = (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '';
            $('input[name="image_h_align' + sfx + '"]').val(ca).trigger('change');
            $('input[name="image_v_align' + sfx + '"]').val(va).trigger('change');
            $('.impulse-align-grid[data-name="image_anchor"] .impulse-align-dot').removeClass('active');
            $(this).addClass('active');
        });
        $(document).on('input change', '#impulse-settings-body .impulse-color-text, #impulse-screen-bar .impulse-color-text', function() {
            var name = $(this).attr('name') || '';
            var $block = $(this).closest('.impulse-dt-line-block');
            if (!$block.length) return;
            var lineNum = $block.data('line');
            var prefix = 'line_' + lineNum;
            
            if (name === prefix + '_color') {
                $block.find('input[name="' + prefix + '_grad_1"]').val($(this).val());
            }
            
            var grad2 = ($block.find('input[name="' + prefix + '_grad_2"].impulse-color-text').val() || '').trim();
            var isGrad = grad2 !== '' && grad2 !== 'transparent';
            $block.find('input[name="' + prefix + '_fill"]').val(isGrad ? 'gradient' : 'solid');
            
        });

        

        $(document).on('change', 'input[name="depth_of_field"]', function() {
            $('.impulse-dt-dof-settings').css({ opacity: this.checked ? '' : '0.35', 'pointer-events': this.checked ? '' : 'none' });
            autoSaveAndPreview();
        });

        
        function _realignMenuSwatches() {
            $('.impulse-menu-sw:visible').each(function(i) {
                var c = i % 3;
                this.style.alignItems = (c === 0) ? 'flex-start' : (c === 2) ? 'flex-end' : 'center';
            });
        }
        $(document).on('change', 'input[name="menu_show_button"]', function() {
            var on = this.checked;
            $('#menu-btnlabel-row').css('display', on ? '' : 'none');
            $('.menu-sw-btn').css('display', on ? 'flex' : 'none');
            _realignMenuSwatches();
        });
        $(document).on('change', 'input[name="pl_show_divider"]', function() {
            $('.menu-sw-divider').css('display', this.checked ? 'flex' : 'none');
            _realignMenuSwatches();
        });
        
        $(document).on('change', 'input[name="depth_effects"]', function() {
            window._dt3dPrevSnap = null; 
            var on = this.checked;
            
            if (on && selectedElementType === 'title' && ($('input[name="la_preset"]').val() || '')) {
                $('input[name="la_preset"]').val('');
                $('.impulse-btn-group[data-name="la_preset"] button').removeClass('active');
            }
            $('input[name="depth_of_field"]').val(on ? '1' : '');
            $('input[name="depth_shadow"]').val(on ? '1' : '');
            var _strokeNow = $('input[name="stroke_enabled"]').is(':checked');

            $('.impulse-dt-dof-settings').css({ opacity: '', 'pointer-events': '' });
            $('.impulse-dt-dof-settings > *').css({ opacity: on ? '' : '0.6', 'pointer-events': on ? '' : 'none' });
            
            if (on) {
                $('.impulse-dt-depth-sliders').css('display', 'block');
            } else {
                var d1 = parseInt($('input[name="line_1_depth"]').val()) || 0;
                var r1 = parseInt($('input[name="line_1_yrot"]').val()) || 0;
                if (d1 === 0 && r1 === 0) $('.impulse-dt-depth-sliders').css('display', 'none');
            }
            autoSaveAndPreview();
        });

        $(document).on('input change', 'input[name="line_1_depth"]', function() {
            var d1 = parseInt($('input[name="line_1_depth"]').val()) || 0;
            var r1 = parseInt($('input[name="line_1_yrot"]').val()) || 0;
            var anyDepth = d1 !== 0 || r1 !== 0;
            $('.impulse-dt-depth-sliders').css('display', anyDepth || $('.impulse-dt-depth-sliders').is(':visible') ? 'block' : 'none');
            var _id = $('.impulse-panel-right').data('element-id');
            if (_id) {
                clearTimeout(window._dtDepthSliderTimer);
                window._dtDepthSliderTimer = setTimeout(function() {
                    var _iframe = document.getElementById('impulse-iframe');
                    if (_iframe && _iframe.contentWindow) {
                        _iframe.contentWindow.postMessage({
                            type: 'impulse-3d-text-update',
                            id: _id,
                            prop: 'lineDepths',
                            value: { 1: d1 }
                        }, '*');
                    }
                }, 30);
            }
        });
        
        $(document).on('input change', 'input[name="line_1_yrot"]', function() {
            var r1 = parseInt($('input[name="line_1_yrot"]').val()) || 0;
            var d1 = parseInt($('input[name="line_1_depth"]').val()) || 0;
            var anyDepth = d1 !== 0 || r1 !== 0;
            $('.impulse-dt-depth-sliders').css('display', anyDepth || $('.impulse-dt-depth-sliders').is(':visible') ? 'block' : 'none');
            var _id = $('.impulse-panel-right').data('element-id');
            if (_id) {
                clearTimeout(window._dtYRotSliderTimer);
                window._dtYRotSliderTimer = setTimeout(function() {
                    var _iframe = document.getElementById('impulse-iframe');
                    if (_iframe && _iframe.contentWindow) {
                        _iframe.contentWindow.postMessage({
                            type: 'impulse-3d-text-update',
                            id: _id,
                            prop: 'lineYRots',
                            value: { 1: r1 }
                        }, '*');
                    }
                }, 30);
            }
        });
        
        $(document).on('input change', 'input[name="line_1_stroke"]', function() {
            var _id = $('.impulse-panel-right').data('element-id');
            if (!_id) return;
            var val  = $(this).val() || '';
            clearTimeout(window._dtStrokeColorTimer);
            window._dtStrokeColorTimer = setTimeout(function() {
                var _iframe = document.getElementById('impulse-iframe');
                if (_iframe && _iframe.contentWindow) {
                    _iframe.contentWindow.postMessage({ type: 'impulse-3d-text-update', id: _id, prop: 'line1stroke', value: val }, '*');
                }
            }, 30);
        });
        $(document).on('input change', 'input[name="mouse_sens"], input[name="orbit_speed"]', function() {
            var _id = $('.impulse-panel-right').data('element-id');
            if (!_id) return;
            var prop = this.name === 'mouse_sens' ? 'mouseSens' : 'orbitSpeed';
            var val  = parseFloat($(this).val()) || 0;
            clearTimeout(window._dtMouseSliderTimer);
            window._dtMouseSliderTimer = setTimeout(function() {
                var _iframe = document.getElementById('impulse-iframe');
                if (_iframe && _iframe.contentWindow) {
                    _iframe.contentWindow.postMessage({ type: 'impulse-3d-text-update', id: _id, prop: prop, value: val }, '*');
                }
            }, 30);
        });
        
        $(document).on('change', 'input[name="stroke_enabled"]', function() {
            window._dt3dPrevSnap = null; 
            var on = this.checked;
            
            if (on && selectedElementType === 'title' && ($('input[name="la_preset"]').val() || '')) {
                $('input[name="la_preset"]').val('');
                $('.impulse-btn-group[data-name="la_preset"] button').removeClass('active');
            }

            
            
            $('.impulse-dt-stroke-controls').css({ opacity: '', 'pointer-events': '' });
            $('.impulse-dt-stroke-controls > *').css({ opacity: on ? '' : '0.6', 'pointer-events': on ? '' : 'none' });

            
            $('.impulse-hdr-bevel-cell').css('visibility', on ? 'visible' : 'hidden');

            
            
            $('[data-line]').find('[style*="flex-shrink:0"]').filter(function() {
                return $(this).find('input[name*="_stroke"]').length > 0;
            }).css({ opacity: on ? '' : '0.35', 'pointer-events': on ? '' : 'none' });
            autoSaveAndPreview();
        });
        
        $(document).on('click', '.impulse-section-collapse', function() {
            var $body = $(this).next('.impulse-section-body');
            if ($body.length) {
                var collapsed = $body.is(':hidden');
                $body.toggle();
                $(this).attr('data-collapsed', collapsed ? '0' : '1');
            }
        });
        
        $(document).on('input', 'input[name="ib_icon_depth"], input[name="ib_title_depth"], input[name="ib_text_depth"]', function() {
            var d1 = parseInt($('input[name="ib_icon_depth"]').val()) || 0;
            var d2 = parseInt($('input[name="ib_title_depth"]').val()) || 0;
            var d3 = parseInt($('input[name="ib_text_depth"]').val()) || 0;
            if (d1 !== 0 || d2 !== 0 || d3 !== 0) {
                $('.impulse-ib-depth-options').show();
            } else {
                $('.impulse-ib-depth-options').hide();
            }
        });
        
        $(document).on('change', 'input[name="ib_dof"]', function() {
            $('.impulse-ib-dof-settings').css({ opacity: this.checked ? '' : '0.35', 'pointer-events': this.checked ? '' : 'none' });
        });
        
        $(document).on('change', 'input[name="ib_chromatic"]', function() {
            $('.impulse-ib-chromatic-settings').css({ opacity: this.checked ? '' : '0.35', 'pointer-events': this.checked ? '' : 'none' });
        });
        
        $(document).on('input', 'textarea[name="title_content"], textarea[name="text_content"]', function() {
            var hasContent = ($('textarea[name="title_content"]').val() || '').trim() !== '' || ($('textarea[name="text_content"]').val() || '').trim() !== '';
            $('.impulse-icon-layout-settings').toggle(hasContent);
            $('.impulse-icon-textalign-settings').toggle(hasContent);
        });

        
        $(document).on('click', '.impulse-btn-group[data-name="type"] button', function(e) {
            var type = $(this).data('value');
            
            if (type === 'products' || type === 'images') {
                if (type === 'products') {
                    $('.impulse-carousel-images').hide();
                    $('.impulse-carousel-products').show();
                } else {
                    $('.impulse-carousel-images').show();
                    $('.impulse-carousel-products').hide();
                }
                
                e.stopImmediatePropagation();
                
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
                
                $(this).closest('.impulse-btn-group').find('input[type="hidden"]').val(type);
                
                autoSaveAndRefresh();
            }
        });

        
        $(document).on('click', '.impulse-btn-group[data-name="content_type"] button', function(e) {
            var ct = $(this).data('value');
            e.stopImmediatePropagation();
            $(this).siblings('button').removeClass('active');
            $(this).addClass('active');
            $(this).closest('.impulse-btn-group').find('input[type="hidden"]').val(ct);
            if (ct === 'images') {
                $('.impulse-carousel-images-section').show();
                $('.impulse-carousel-data-section').hide();
            } else {
                $('.impulse-carousel-images-section').hide();
                $('.impulse-carousel-data-section').show();
            }
            autoSaveAndRefresh();
        });

        

        
        $(document).on('click', '.impulse-slider-slide-btn', function() {
            var index = parseInt($(this).data('index'));
            var slides = [];
            try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(e) {}

            var currentIndex = parseInt($('input[name="current_slide"]').val() || 0);
            if (slides[currentIndex]) {
                slides[currentIndex].background = $('input[name="slide_bg_color"]').val() || ''+ImpC.border+'';
                slides[currentIndex].bg_image = $('input[name="slide_bg_image"]').val() || '';
            }
            
            $('input[name="slides"]').val(JSON.stringify(slides));
            $('input[name="current_slide"]').val(index).trigger('change');

            if (window.currentSelectedEl) {
                renderSettingsPanel(window.currentSelectedEl.data('type'), window.currentSelectedEl.data('settings') || {});
            }
        });

        $(document).on('change', 'input[name="slide_bg_color"]', function() {
            var slides = [];
            try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(e) {}
            var currentIndex = parseInt($('input[name="current_slide"]').val() || 0);
            if (slides[currentIndex]) {
                slides[currentIndex].background = $(this).val();
                
                $('input[name="slides"]').val(JSON.stringify(slides));
                
                var es = $('.impulse-panel-right').data('existing-settings') || {};
                es.slides = slides;
                $('.impulse-panel-right').data('existing-settings', es);
                
                $('.impulse-slider-slide-btn[data-index="' + currentIndex + '"]').css('background', $(this).val());
                $('.impulse-new-slide-btn[data-index="' + currentIndex + '"]').css('background', $(this).val());
                
                try {
                    var iframe = document.getElementById('impulse-iframe');
                    var elId = $('.impulse-panel-right').data('element-id');
                    if (iframe && iframe.contentDocument && elId) {
                        var slideEl = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-carousel-slide[data-index="' + currentIndex + '"]');
                        if (slideEl) slideEl.style.background = $(this).val();
                    }
                } catch(e) {}
                
                autoSaveAndPreview();
            }
        });

        

        
        function saveNewSlideSettings(slides) {
            var currentIndex = parseInt($('input[name="current_slide"]').val() || 0);
            if (slides[currentIndex]) {
                slides[currentIndex].background = $('input[name="slide_bg_color"]').val() || '';
                slides[currentIndex].valign = $('input[name="slide_valign"]').val() || 'center';
            }
            return slides;
        }

        $(document).on('click', '.impulse-new-slide-btn', function() {
            var index = parseInt($(this).data('index'));
            var slides = [];
            try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(e) {}

            slides = saveNewSlideSettings(slides);

            $('input[name="slides"]').val(JSON.stringify(slides));
            $('input[name="current_slide"]').val(index);

            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            var newSettings = $.extend({}, existingSettings, {
                slides: slides,
                current_slide: index
            });
            $('.impulse-panel-right').data('existing-settings', newSettings);
            renderSettingsPanel(selectedElementType || 'slider', newSettings);

            var elId = $('.impulse-panel-right').data('element-id');
            if (elId) {
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentDocument) {
                    var sliderEl = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-new-slider');
                    if (sliderEl && sliderEl._goToSlide) {
                        sliderEl._goToSlide(index);
                        sliderEl.dataset.currentSlide = index;
                    } else {
                        
                        var track = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-carousel-slides');
                        if (track) track.style.transform = 'translateX(-' + (index * 100) + '%)';
                    }
                }
            }
            
            autoSaveAndPreview();
        });

        (function() {
            var dragFromIndex = null;

            $(document).on('dragstart', '.impulse-new-slide-btn', function(e) {
                dragFromIndex = parseInt($(this).data('index'));
                e.originalEvent.dataTransfer.effectAllowed = 'move';
                e.originalEvent.dataTransfer.setData('text/plain', dragFromIndex);
                $(this).css('opacity', '0.4');
            });

            $(document).on('dragend', '.impulse-new-slide-btn', function() {
                dragFromIndex = null;
                $('.impulse-new-slide-btn').css({ opacity: '', outline: '' });
            });

            $(document).on('dragover', '.impulse-new-slide-btn', function(e) {
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';
                var toIndex = parseInt($(this).data('index'));
                if (toIndex !== dragFromIndex) {
                    $(this).css('outline', '2px solid '+ImpC.text+'');
                }
            });

            $(document).on('dragleave', '.impulse-new-slide-btn', function() {
                $(this).css('outline', '');
            });

            $(document).on('drop', '.impulse-new-slide-btn', function(e) {
                e.preventDefault();
                $(this).css('outline', '');
                var toIndex = parseInt($(this).data('index'));
                if (dragFromIndex === null || toIndex === dragFromIndex) return;

                var slides = [];
                try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(err) {}
                slides = saveNewSlideSettings(slides);

                var tmp = slides[dragFromIndex];
                slides[dragFromIndex] = slides[toIndex];
                slides[toIndex] = tmp;

                var newCurrent = toIndex;
                $('input[name="slides"]').val(JSON.stringify(slides));
                $('input[name="current_slide"]').val(newCurrent);

                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var newSettings = $.extend({}, existingSettings, { slides: slides, current_slide: newCurrent });
                $('.impulse-panel-right').data('existing-settings', newSettings);
                renderSettingsPanel(selectedElementType || 'slider', newSettings);
                autoSaveAndRefresh();
            });
        })();

        
        
        $(document).on('contextmenu', '.impulse-new-slide-btn', function(e) {
            e.preventDefault(); e.stopPropagation();
            var idx = parseInt($(this).data('index'));
            var slides = [];
            try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(err) {}
            window._slideCtxIndex = idx;
            var html = '';
            html += window.ctxItem('slide-add', 'Add slide');
            html += window.ctxItem('slide-duplicate', 'Duplicate');
            if (slides.length > 1) {
                html += window.ctxDiv();
                html += window.ctxItem('slide-delete', 'Delete', '', 'danger');
            }
            window.ctxShow($('#impulse-context-menu'), e.clientX, e.clientY, html);
        });

        $(document).on('click', '#impulse-context-menu .impulse-context-item', function() {
            var action = $(this).data('action');
            if (!action || !action.startsWith('slide-')) return;
            var ctxIdx = window._slideCtxIndex;
            window.ctxHide();
            var slides = [];
            try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(err) {}
            slides = saveNewSlideSettings(slides);

            if (action === 'slide-add') {
                if (slides.length >= 20) return;
                var newIdx = slides.length;
                slides.push({ id: 'slide-' + (newIdx + 1) + '-' + Date.now(), background: '', valign: 'center' });
                _applySlideChange(slides, newIdx);
            } else if (action === 'slide-duplicate') {
                if (slides.length >= 20) return;
                if (!slides[ctxIdx]) return;
                var copy = JSON.parse(JSON.stringify(slides[ctxIdx]));
                copy.id = 'slide-' + (slides.length + 1) + '-' + Date.now();
                slides.splice(ctxIdx + 1, 0, copy);
                _applySlideChange(slides, ctxIdx + 1);
            } else if (action === 'slide-delete') {
                if (slides.length <= 1) return;
                slides.splice(ctxIdx, 1);
                _applySlideChange(slides, Math.min(ctxIdx, slides.length - 1));
            }
        });

        function _applySlideChange(slides, newCurrent) {
            $('input[name="slides"]').val(JSON.stringify(slides));
            $('input[name="current_slide"]').val(newCurrent);
            $('input[name="slide_count"]').val(slides.length);
            var es = $('.impulse-panel-right').data('existing-settings') || {};
            es = $.extend({}, es, { slides: slides, current_slide: newCurrent });
            $('.impulse-panel-right').data('existing-settings', es);
            renderSettingsPanel(selectedElementType || 'slider', es);
            autoSaveAndRefresh();
        }

        $(document).on('click', '.impulse-btn-group[data-name="slide_valign"] button', function(e) {
            e.stopPropagation();
            var $group = $(this).closest('.impulse-btn-group');
            $group.find('button').removeClass('active');
            $(this).addClass('active');
            var value = $(this).data('value');
            $group.find('input[type="hidden"]').val(value);

            var slides = [];
            try { slides = JSON.parse($('input[name="slides"]').val() || '[]'); } catch(e) {}
            var currentIndex = parseInt($('input[name="current_slide"]').val() || 0);
            if (slides[currentIndex]) {
                slides[currentIndex].valign = value;
                
                $('input[name="slides"]').val(JSON.stringify(slides));
                
                var es = $('.impulse-panel-right').data('existing-settings') || {};
                es.slides = slides;
                $('.impulse-panel-right').data('existing-settings', es);
                
                var valignMap = { top: 'flex-start', center: 'center', bottom: 'flex-end', between: 'space-between', around: 'space-around', evenly: 'space-evenly' };
                try {
                    var iframe = document.getElementById('impulse-iframe');
                    var elId = $('.impulse-panel-right').data('element-id');
                    if (iframe && iframe.contentDocument && elId) {
                        var dz = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-carousel-slide[data-index="' + currentIndex + '"] .impulse-new-slider-dropzone');
                        if (dz) dz.style.justifyContent = valignMap[value] || 'center';
                    }
                } catch(e) {}
            }
            autoSaveAndPreview();
        });

        

        
        
        $(document).on('click', '.impulse-acc-expand-btn', function(e) {
            e.stopPropagation();
            var $item = $(this).closest('.impulse-unfold-item-edit');
            var $textarea = $item.find('.impulse-unfold-content');
            var $chevron = $(this).find('svg');
            var isOpen = $textarea.is(':visible');
            
            $('.impulse-unfold-editor .impulse-unfold-content').hide();
            $('.impulse-acc-expand-btn svg').css('transform', '');
            
            if (!isOpen) {
                $textarea.show().trigger('focus');
                $chevron.css('transform', 'rotate(180deg)');
            }
        });
        
        $(document).on('click', '.impulse-add-unfold-item', function() {
            var items = [];
            try { items = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            items.push({title: 'New Item', content: 'Item content'});
            $('input[name="items"]').val(JSON.stringify(items));
            rebuildAccordionEditor(items);
            saveItemsNow(true);
        });

        $(document).on('click', '.impulse-remove-unfold-item', function() {
            var $item = $(this).closest('.impulse-unfold-item-edit');
            var index = $item.data('index');
            var items = [];
            try { items = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            items.splice(index, 1);
            $('input[name="items"]').val(JSON.stringify(items));
            rebuildAccordionEditor(items);
            saveItemsNow(true);
        });

        var _accItemSaveTimer = null;
        $(document).on('input', '.impulse-unfold-title, .impulse-unfold-content', function() {
            var items = [];
            $('.impulse-unfold-item-edit').each(function() {
                items.push({
                    title: $(this).find('.impulse-unfold-title').val(),
                    content: $(this).find('.impulse-unfold-content').val()
                });
            });
            
            $('input[name="items"]').val(JSON.stringify(items));
            
            var _aiId = $('.impulse-panel-right').data('element-id');
            var _aiIframe = document.getElementById('impulse-iframe');
            if (_aiIframe && _aiIframe.contentDocument && _aiId) {
                var _aiTiles = _aiIframe.contentDocument.querySelectorAll('.impulse-el[data-id="' + _aiId + '"] .impulse-acc-tile');
                _aiTiles.forEach(function(tile, i) {
                    if (!items[i]) return;
                    var titleEl = tile.querySelector('.impulse-acc-tile-title');
                    var backEl = tile.querySelector('.impulse-acc-tile-back');
                    if (titleEl) titleEl.textContent = items[i].title || '';
                    if (backEl) backEl.innerHTML = items[i].content || '';
                });
            }
            
            clearTimeout(_accItemSaveTimer);
            showSaveStatus(true);
            _accItemSaveTimer = setTimeout(function() {
                var id = $('.impulse-panel-right').data('element-id');
                if (!id) return;
                var existing = $('.impulse-panel-right').data('existing-settings') || {};
                var settings = collectSettingsFromPanel(existing);
                var merged = $.extend({}, existing, settings);
                $('.impulse-panel-right').data('existing-settings', merged);
                enqueueSave(id, merged, function(ok) { if (ok) showSaveStatus(); });
            }, 400);
        });
        
        function rebuildAccordionEditor(items) {
            var html = '';
            items.forEach(function(item, i) {
                html += '<div class="impulse-unfold-item-edit" data-index="' + i + '" style="margin-top:' + (i > 0 ? '3' : '0') + 'px">';
                html += '<div class="impulse-acc-item-header" style="display:flex;gap:3px;align-items:center">';
                html += '<span class="impulse-unfold-drag" style="cursor: default;color:'+ImpC.dim+';display:flex;align-items:center;flex-shrink:0"><svg width="8" height="14" viewBox="0 0 8 14" fill="currentColor"><circle cx="2" cy="2" r="1.2"/><circle cx="6" cy="2" r="1.2"/><circle cx="2" cy="7" r="1.2"/><circle cx="6" cy="7" r="1.2"/><circle cx="2" cy="12" r="1.2"/><circle cx="6" cy="12" r="1.2"/></svg></span>';
                html += '<input type="text" class="impulse-unfold-title" value="' + (item.title || '').replace(/"/g, '&quot;') + '" placeholder="Item ' + (i+1) + '" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:12px;color:'+ImpC.text+';box-sizing:border-box;outline:none;min-width:0">';
                html += '<button type="button" class="impulse-acc-expand-btn" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Edit content"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><polyline points="6 9 12 15 18 9"/></svg></button>';
                html += '<button type="button" class="impulse-remove-unfold-item" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                html += '</div>';
                html += '<textarea class="impulse-unfold-content" data-index="' + i + '" placeholder="Back side content..." style="display:none;width:100%;min-height:36px;padding:4px 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';resize:vertical;box-sizing:border-box;margin-top:3px;line-height:1.4;outline:none">' + (item.content || '').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
                html += '</div>';
            });
            $('.impulse-unfold-editor').html(html);
        }

        

        
        function saveItemsNow(refresh) {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var settings = collectSettingsFromPanel(existing);
            var merged = $.extend({}, existing, settings);
            $('.impulse-panel-right').data('existing-settings', merged);
            showSaveStatus(true);
            enqueueSave(id, merged, function(ok) {
                if (!ok) return;
                showSaveStatus();
                if (refresh) refreshElement(id);
            });
        }
        var _ilItemSaveTimer = null;

        

        

        $(document).on('click', '.impulse-add-icon-list-item', function() {
            var items = [];
            try { items = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            items.push({icon: 'circle', text: '', url: ''});
            $('input[name="items"]').val(JSON.stringify(items));
            rebuildIconListEditor(items);
            saveItemsNow(true);
        });

        $(document).on('click', '.impulse-btn-group[data-name="columns"] button', function() {
            var elType = $('.impulse-panel-right').data('element-type') || selectedElementType;
            if (elType !== 'table') return;
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId) return;
            var _ilMerged = $.extend({}, $('.impulse-panel-right').data('existing-settings') || {}, collectSettingsFromPanel($('.impulse-panel-right').data('existing-settings') || {}));
            $('.impulse-panel-right').data('existing-settings', _ilMerged);
            $('#impulse-settings-body').html(buildSettingsForm('table', _ilMerged, []));
            impulseAnimatorSvgAutoLoad();
        });

        

        

        
        $(document).on('click', '.impulse-btn-group[data-name="style"] button', function() {
            var elType = $('.impulse-panel-right').data('element-type') || selectedElementType;
            if (elType !== 'divider') return;
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId) return;

            
            var merged = $.extend({}, $('.impulse-panel-right').data('existing-settings') || {}, collectSettingsFromPanel($('.impulse-panel-right').data('existing-settings') || {}));
            $(document).off('.dividerRebuild');
            var html = buildSettingsForm('divider', merged, []);
            var $body = $('#impulse-settings-body');
            $body.off('change.dividerRebuild input.dividerRebuild');
            $body.html(html);
            $('.impulse-panel-right').data('existing-settings', merged);
        });

        $(document).on('click', '.impulse-btn-group[data-name="map_shape"] button', function() {
            var elType = $('.impulse-panel-right').data('element-type') || selectedElementType;
            if (elType !== 'map') return;
            var elId = $('.impulse-panel-right').data('element-id');
            if (!elId) return;
            var _merged = $.extend({}, $('.impulse-panel-right').data('existing-settings') || {}, collectSettingsFromPanel($('.impulse-panel-right').data('existing-settings') || {}));
            $('.impulse-panel-right').data('existing-settings', _merged);
            $('#impulse-settings-body').html(buildSettingsForm(elType, _merged, []));
        });

        $(document).on('input', 'input[name="neon_preset"]', function() {
            if ((selectedElementType || '') !== 'divider') return;
            var presets = [
                {c:'#ff1a1a',c2:'#ff6644',n:'Red'},
                {c:'#ff0066',c2:'#ff33aa',n:'Pink'},
                {c:'#9933ff',c2:'#cc66ff',n:'Violet'},
                {c:'#0066ff',c2:'#3399ff',n:'Blue'},
                {c:'#00ccff',c2:'#00ffff',n:'Cyan'},
                {c:'#00ff66',c2:'#33ff99',n:'Green'},
                {c:'#ffcc00',c2:'#ffff33',n:'Yellow'},
                {c:'#ff6600',c2:'#ff9933',n:'Orange'},
                {c:'#ffffff',c2:''+ImpC.text+'',n:'White'}
            ];
            var idx = parseInt($(this).val()) || 0;
            var p = presets[idx] || presets[4];
            
            var $c1 = $('input[name="color"]');
            var $c2 = $('input[name="color2"]');
            if ($c1.length) {
                $c1.val(p.c).trigger('change');
                $c1.closest('.impulse-color-swatch-wrap').find('.impulse-color-swatch').css('background', p.c);
            }
            if ($c2.length) {
                $c2.val(p.c2).trigger('change');
                $c2.closest('.impulse-color-swatch-wrap').find('.impulse-color-swatch').css('background', p.c2);
            }
            autoSaveAndRefresh();
        });

        

        
        $(document).on('click', '.impulse-remove-icon-list-item', function() {
            var $item = $(this).closest('.impulse-table-item-edit');
            var index = $item.data('index');
            var items = [];
            try { items = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            items.splice(index, 1);
            $('input[name="items"]').val(JSON.stringify(items));
            rebuildIconListEditor(items);
            saveItemsNow(true);
        });

        $(document).on('input', '.impulse-table-text, .impulse-table-col2, .impulse-table-col3', function() {
            var items = [];
            $('.impulse-table-item-edit').each(function() {
                var iconName = $(this).data('icon') || 'circle';
                var isUrlMode = $(this).hasClass('impulse-url-mode');
                var inputVal = $(this).find('.impulse-table-text').val();
                var item = { icon: iconName, text: '', url: '' };
                if (isUrlMode) {
                    item.url = inputVal;
                    var storedItems = [];
                    try { storedItems = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
                    var idx = $(this).data('index');
                    if (storedItems[idx]) item.text = storedItems[idx].text || '';
                } else {
                    item.text = inputVal;
                    item.url = $(this).data('url') || '';
                }
                var c2 = $(this).find('.impulse-table-col2').val();
                var c3 = $(this).find('.impulse-table-col3').val();
                if (c2 !== undefined) item.col2 = c2;
                if (c3 !== undefined) item.col3 = c3;
                items.push(item);
            });
            $('input[name="items"]').val(JSON.stringify(items));
            clearTimeout(_ilItemSaveTimer);
            _ilItemSaveTimer = setTimeout(function() { saveItemsNow(false); }, 600);
        });

        
        
        $(document).on('click', '.impulse-table-url-btn', function() {
            var $row = $(this).closest('.impulse-table-item-edit');
            if ($row.find('.impulse-table-url-input').length) return; 
            var idx = $row.data('index');
            var storedItems = [];
            try { storedItems = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            var currentUrl = (storedItems[idx] && storedItems[idx].url) || $row.data('url') || '';
            var $label = $row.find('.impulse-table-label');
            $label.hide();
            var $input = $('<input type="text" class="impulse-table-url-input" placeholder="https://..." value="' + escapeHtml(currentUrl) + '" style="flex:1;min-width:0;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">');
            $input.insertAfter($label);
            $input.focus().select();
        });

        $(document).on('keydown', '.impulse-table-url-input', function(e) {
            if (e.key === 'Enter') { e.preventDefault(); $(this).blur(); }
            else if (e.key === 'Escape') { e.preventDefault(); $(this).data('cancel', true).blur(); }
        });
        $(document).on('blur', '.impulse-table-url-input', function() {
            var $input = $(this);
            var cancelled = $input.data('cancel');
            var $row = $input.closest('.impulse-table-item-edit');
            var idx = $row.data('index');
            var $btn = $row.find('.impulse-table-url-btn');
            var storedItems = [];
            try { storedItems = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            if (!cancelled) {
                var url = $input.val().trim();
                if (storedItems[idx]) storedItems[idx].url = url;
                $row.data('url', url);
                if (url) {
                    $row.addClass('impulse-url-mode');
                    $btn.addClass('impulse-url-active').css({'background': ''+ImpC.border+'', 'border-color': ''+ImpC.dim+''}).find('svg').attr('stroke', ''+ImpC.white+'');
                } else {
                    $row.removeClass('impulse-url-mode');
                    $btn.removeClass('impulse-url-active').css({'background': ''+ImpC.panel+'', 'border-color': ''+ImpC.border+''}).find('svg').attr('stroke', ''+ImpC.muted+'');
                }
                $('input[name="items"]').val(JSON.stringify(storedItems)).trigger('change');
            }
            $input.remove();
            $row.find('.impulse-table-label').show();
        });

        var iconListEditIndex = -1;
        $(document).on('click', '.impulse-table-icon-btn', function(e) {
            
            if ($(e.target).hasClass('impulse-icon-copy-down')) return;
            e.preventDefault();
            e.stopPropagation();
            iconListEditIndex = $(this).data('index');
            var $btn = $(this);
            
            loadIcons();
            $('#impulse-icon-modal').data('target', 'icon_list_item').data('icon-list-btn', $btn).show();
        });

        $(document).on('click', '.impulse-icon-copy-down', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $currentRow = $(this).closest('.impulse-table-item-edit');
            var $nextRow = $currentRow.next('.impulse-table-item-edit');
            if (!$nextRow.length) return;
            
            var icon = $currentRow.data('icon') || 'circle';
            $nextRow.data('icon', icon);
            $nextRow.find('.impulse-table-icon-btn').html(lucideSvg(icon, 12) + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span>');

            var items = [];
            $('.impulse-table-item-edit').each(function() {
                var isUrlMode = $(this).hasClass('impulse-url-mode');
                var inputVal = $(this).find('.impulse-table-text').val();
                var item = {
                    icon: $(this).data('icon') || 'circle',
                    text: isUrlMode ? '' : inputVal,
                    url: isUrlMode ? inputVal : ($(this).data('url') || '')
                };
                var c2 = $(this).find('.impulse-table-col2').val();
                var c3 = $(this).find('.impulse-table-col3').val();
                if (c2 !== undefined) item.col2 = c2;
                if (c3 !== undefined) item.col3 = c3;
                items.push(item);
            });
            $('input[name="items"]').val(JSON.stringify(items)).trigger('change');
            autoSaveAndRefresh();
        });
        
        function rebuildIconListEditor(items) {
            var html = '';
            items.forEach(function(item, i) {
                var iconName = item.icon || 'circle';
                var hasUrl = !!(item.url);
                var label = item.text || 'Item ' + (i + 1);
                if (label.length > 24) label = label.substring(0, 22) + '...';
                html += '<div class="impulse-table-item-edit' + (hasUrl ? ' impulse-url-mode' : '') + '" data-index="' + i + '" data-icon="' + iconName + '" data-url="' + (item.url || '').replace(/"/g, '&quot;') + '" style="margin-bottom:4px;display:flex;gap:4px;align-items:center">';
                html += '<span class="impulse-table-drag" style="cursor: default;padding:2px;color:#666"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
                html += '<button type="button" class="impulse-table-icon-btn" data-index="' + i + '" style="width:26px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.muted+';flex-shrink:0;box-sizing:border-box;position:relative">' + lucideSvg(iconName, 12) + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span></button>';
                html += '<span style="flex:1;min-width:0;font-size:11px;color:'+ImpC.muted+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + (item.text || 'Item ' + (i+1)).replace(/</g, '&lt;') + '</span>';
                html += '<input type="hidden" class="impulse-table-text" value="' + (item.text || '').replace(/"/g, '&quot;') + '">';
                html += '<button type="button" class="impulse-table-url-btn' + (hasUrl ? ' impulse-url-active' : '') + '" style="width:26px;height:26px;flex-shrink:0;background:' + (hasUrl ? ''+ImpC.border+'' : ''+ImpC.panel+'') + ';border:1px solid ' + (hasUrl ? ''+ImpC.dim+'' : ''+ImpC.border+'') + ';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Toggle URL"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="' + (hasUrl ? ''+ImpC.white+'' : ''+ImpC.muted+'') + '" stroke-width="2.5"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></button>';
                html += '<button type="button" class="impulse-remove-icon-list-item" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                html += '</div>';
            });
            $('.impulse-table-editor').html(html);
            initIconListSortable();
        }

        var iconListSortable = null;
        function initIconListSortable() {
            var list = document.querySelector('.impulse-table-editor');
            if (list && typeof Sortable !== 'undefined') {
                if (iconListSortable) iconListSortable.destroy();
                iconListSortable = new Sortable(list, {
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    handle: '.impulse-table-drag',
                    onEnd: function() {
                        
                        var items = [];
                        $('.impulse-table-item-edit').each(function() {
                            var isUrlMode = $(this).hasClass('impulse-url-mode');
                            var inputVal = $(this).find('.impulse-table-text').val();
                            var item = {
                                icon: $(this).data('icon') || 'circle',
                                text: isUrlMode ? '' : inputVal,
                                url: isUrlMode ? inputVal : ($(this).data('url') || '')
                            };
                            
                            if (isUrlMode) {
                                var storedItems = [];
                                try { storedItems = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
                                var idx = $(this).data('index');
                                if (storedItems[idx]) item.text = storedItems[idx].text || '';
                            }
                            var c2 = $(this).find('.impulse-table-col2').val();
                            var c3 = $(this).find('.impulse-table-col3').val();
                            if (c2 !== undefined) item.col2 = c2;
                            if (c3 !== undefined) item.col3 = c3;
                            items.push(item);
                        });
                        $('input[name="items"]').val(JSON.stringify(items));
                        autoSaveAndRefresh();
                    }
                });
            }
        }

        
        
        var chartEntriesSortable = null;
        function initChartEntriesSortable() {
            var list = document.getElementById('impulse-chart-entries-list');
            if (list && typeof Sortable !== 'undefined') {
                if (chartEntriesSortable) chartEntriesSortable.destroy();
                chartEntriesSortable = new Sortable(list, {
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    handle: '.impulse-chart-entry-drag',
                    onEnd: function() {
                        var entries = [];
                        $('#impulse-chart-entries-list .impulse-chart-entry-row').each(function(newIdx) {
                            entries.push({
                                label: $(this).find('.ch-row-label').val() || '',
                                value: parseFloat($(this).find('.ch-row-value').val()) || 0,
                                color: $(this).find('.ch-row-color').val() || ''
                            });
                            
                            $(this).attr('data-index', newIdx).data('index', newIdx);
                        });
                        $('input[name="chart_entries"]').val(JSON.stringify(entries));
                        autoSaveAndRefresh();
                    }
                });
            }
        }

        var priceListSortable = null;
        function initPriceListSortable() {
            var list = document.querySelector('.impulse-pl-items');
            if (list && typeof Sortable !== 'undefined') {
                if (priceListSortable) priceListSortable.destroy();
                priceListSortable = new Sortable(list, {
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    handle: '.impulse-pl-drag',
                    onEnd: function() {
                        
                        $('.impulse-pl-items .impulse-pl-item').each(function(i) {
                            $(this).data('index', i).attr('data-index', i);
                            $(this).find('[data-index]').data('index', i).attr('data-index', i);
                            $(this).find('.impulse-pl-icon-btn').data('index', i).attr('data-index', i);
                        });
                        collectPriceListItems();
                        autoSaveAndRefresh();
                    }
                });
            }
        }

        

        
        $(document).on('click', '.impulse-btn-group[data-name="trigger"] button', function() {
            var trigger = $(this).data('value');
            $('.impulse-modal-trigger-timer, .impulse-modal-trigger-scroll').hide();
            if (trigger === 'timer') {
                $('.impulse-modal-trigger-timer').show();
            } else if (trigger === 'scroll') {
                $('.impulse-modal-trigger-scroll').show();
            }
        });

        $(document).on('click', '.impulse-copy-popup-id', function() {
            var id = $('input[name="popup_id"]').val() || $('input[name="oc_id"]').val() || '';
            if (id) {
                navigator.clipboard.writeText('#' + id).then(function() {
                    window.showToast('Copied #' + id);
                });
            }
        });

        

        

        $(document).on('click', '#impulse-grid-fill-images', function() {
            var gridId = $('.impulse-panel-right').data('element-id');
            if (!gridId) return;
            openImglibPicker({ label: 'Fill Grid from Library', multiple: true, noFocal: true }, function(attachments) {
                if (!attachments || !attachments.length) return;
                attachments.forEach(function(a) {
                    addElementWithSettings('image', {
                        image_id: a.id,
                        image_src: a.url,
                        width: 100,
                        alt: a.alt || a.filename || ''
                    }, gridId, -1);
                });
            });
        });

        

        
        
        $(document).on('click', '.impulse-grid-select-parent-section', function() {
            var gridId = $('.impulse-panel-right').data('element-id');
            if (!gridId) return;
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe ? iframe.contentDocument : null;
            if (!doc) return;
            var gridEl = doc.querySelector('.impulse-el[data-id="' + gridId + '"]');
            if (!gridEl) return;
            var node = gridEl.parentElement;
            while (node && node !== doc.body) {
                if (node.classList && node.classList.contains('impulse-el') &&
                    node.getAttribute('data-type') === 'section') {
                    var parentId = node.getAttribute('data-id');
                    if (parentId && typeof openSettings === 'function') {
                        openSettings(parentId, 'section');
                    }
                    return;
                }
                node = node.parentElement;
            }
        });

        

        
        $(document).on('click', '[data-name="animation_type"] button, [data-name="animation_type_row2"] button', function(e) {
            e.stopPropagation();
            var type = $(this).data('value');

            $('input[name="animation_type"]').val(type).trigger('change');

            $('[data-name="animation_type"] button, [data-name="animation_type_row2"] button').removeClass('active');
            $(this).addClass('active');

            autoSaveAndRefresh();
        });
        
        $(document).on('change', 'input[name="animation_type"]', function() {
            var type = $(this).val();

            if (type === 'flip') {
                $('.impulse-flip-direction-setting').show();
                $('.impulse-slide-direction-setting').hide();
            } 
            
            else if (type === 'slide' || type === 'push') {
                $('.impulse-flip-direction-setting').hide();
                $('.impulse-slide-direction-setting').show();
            }
            
            else {
                $('.impulse-flip-direction-setting').hide();
                $('.impulse-slide-direction-setting').hide();
            }
        });

        $(document).on('click', '.impulse-flip-direction-setting button, .impulse-slide-direction-setting button', function(e) {
            e.stopPropagation();
            var $group = $(this).closest('.impulse-btn-group');
            $group.find('button').removeClass('active');
            $(this).addClass('active');
            $group.find('input[type="hidden"]').val($(this).data('value'));
            autoSaveAndRefresh();
        });

        

        $(document).on('click', '.impulse-flip-tab', function() {
            var tab = $(this).data('tab');

            $('.impulse-flip-tab').css({
                'border-bottom-color': 'transparent',
                'color': '#666'
            }).removeClass('active');
            $(this).css({
                'border-bottom-color': ''+ImpC.surface2+'',
                'color': ''+ImpC.surface2+''
            }).addClass('active');

            $('.impulse-flip-content').hide();
            $('.impulse-flip-content[data-tab="' + tab + '"]').show();
        });

        

        

        
        function openLightboxMediaLibrary() {
            openImglibPicker({ label: 'Select Image' }, function(attachment) {
                $('input[name="image_url"]').val(attachment.url);
                var id = $('.impulse-panel-right').data('element-id');
                if (id) {
                    autoSaveAndRefresh();
                    setTimeout(function() { loadElementSettings(id); }, 500);
                }
            });
        }

        $(document).on('click', '.impulse-btn-group[data-name="trigger_type"] button', function() {
            var triggerType = $(this).data('value');
            if (triggerType === 'button') {
                $('.impulse-lightbox-button-settings').show();
                $('.impulse-lightbox-icon-settings').hide();
            } else if (triggerType === 'icon') {
                $('.impulse-lightbox-button-settings').hide();
                $('.impulse-lightbox-icon-settings').show();
            } else {
                $('.impulse-lightbox-button-settings').hide();
                $('.impulse-lightbox-icon-settings').hide();
            }
        });

        

        var editingPricingPlanIndex = -1;

        $(document).on('change', 'input[name="show_toggle"]', function() {
            if ($(this).is(':checked')) {
                $('.impulse-yearly-discount-setting').show();
                $('.impulse-toggle-label-color').css({'opacity': '1', 'pointer-events': 'auto'});
            } else {
                $('.impulse-yearly-discount-setting').hide();
                $('.impulse-toggle-label-color').css({'opacity': '0.4', 'pointer-events': 'none'});
            }
            autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-icon-style-btn', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $btn = $(this);
            var type = $btn.data('type'); 
            var currentIcon = $('input[name="' + type + '_icon"]').val() || $('input[name="' + type + '"]').val() || (type === 'check' ? 'plus-square' : (type === 'unfold_icon' || type === 'toggle_icon') ? 'chevron-down' : 'x');

            $('.impulse-icon-picker-modal').remove();

            var checkIcons = [
                {v: 'plus-square', l: 'Plus Square'},
                {v: 'check-square', l: 'Check Square'},
                {v: 'check-circle', l: 'Check Circle'},
                {v: 'check', l: 'Check'},
                {v: 'plus-circle', l: 'Plus Circle'},
                {v: 'circle-dot', l: 'Circle Dot'}
            ];
            var crossIcons = [
                {v: 'x', l: 'X'},
                {v: 'x-square', l: 'X Square'},
                {v: 'x-circle', l: 'X Circle'},
                {v: 'minus-square', l: 'Minus Square'},
                {v: 'minus-circle', l: 'Minus Circle'},
                {v: 'square', l: 'Empty Square'}
            ];
            var unfoldIcons = [
                {v: 'chevron-down', l: 'Chevron'},
                {v: 'plus', l: 'Plus'},
                {v: 'plus-circle', l: 'Plus Circle'},
                {v: 'circle-plus', l: 'Circle Plus'},
                {v: 'arrow-down', l: 'Arrow'},
                {v: 'caret-down', l: 'Caret'}
            ];
            var icons = type === 'check' ? checkIcons : (type === 'unfold_icon' || type === 'toggle_icon') ? unfoldIcons : crossIcons;

            var btnOffset = $btn.offset();
            var btnHeight = $btn.outerHeight();
            var btnWidth = $btn.outerWidth();
            var modalAlign = $btn.data('modal-align') || 'right';

            var modalWidth = 6 * 24 + 12;
            var leftPos = modalAlign === 'left' ? (btnOffset.left + btnWidth - modalWidth) : (btnOffset.left - 40);

            var modal = '<div class="impulse-icon-picker-modal" style="position:fixed;top:' + (btnOffset.top + btnHeight + 4) + 'px;left:' + leftPos + 'px;background:'+ImpC.surface+';border:1px solid '+ImpC.border+';border-radius:4px;padding:6px;z-index:1000030;box-shadow:0 4px 12px rgba(0,0,0,0.3);opacity:0;transform:translateY(-4px);transition:opacity 0.15s ease-in-out,transform 0.15s ease-in-out">';
            modal += '<div style="display:grid;grid-template-columns:repeat(6,1fr);gap:0">';
            icons.forEach(function(icon, idx) {
                var isActive = currentIcon === icon.v;
                var borderLeft = idx > 0 ? 'border-left:1px solid '+ImpC.border+';' : '';
                modal += '<button type="button" class="impulse-icon-option" data-value="' + icon.v + '" data-type="' + type + '" style="width:24px;height:24px;background:transparent;border:none;' + borderLeft + 'cursor:pointer;display:flex;align-items:center;justify-content:center;color:' + (isActive ? ''+ImpC.white+'' : '#666') + '" title="' + icon.l + '">' + getFeatureIconPreview(icon.v, isActive ? ''+ImpC.white+'' : '#666') + '</button>';
            });
            modal += '</div></div>';
            
            $('body').append(modal);

            setTimeout(function() {
                $('.impulse-icon-picker-modal').css({opacity: 1, transform: 'translateY(0)'});
            }, 10);
        });

        $(document).on('click', '.impulse-icon-option', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var value = $(this).data('value');
            var type = $(this).data('type');

            var inputName = (type === 'unfold_icon' || type === 'toggle_icon') ? type : type + '_icon';

            var $panel = $('.impulse-panel-right');
            var $input = $panel.find('input[name="' + inputName + '"]');
            if ($input.length) {
                $input.val(value);
            }

            $panel.find('.impulse-icon-style-btn[data-type="' + type + '"]').html(getFeatureIconPreview(value, ''+ImpC.muted+''));
            $('.impulse-icon-picker-modal').remove();
            
            autoSaveAndRefresh();
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.impulse-icon-style-btn, .impulse-table-icon-btn, .impulse-icon-picker-modal').length) {
                $('.impulse-icon-picker-modal').remove();
            }
        });

        $(document).on('click', '.impulse-btn-group[data-name="columns"] button', function() {
            var columns = $(this).data('value');
            if (columns === '1' || columns === 1) {
                $('.impulse-equal-height-row').hide();
                
                $('input[name="equal_height"]').prop('checked', true);
                
                $('.impulse-column-gap-wrapper').hide();

                
                $('.impulse-text-height-wrapper').hide();
            } else {
                $('.impulse-equal-height-row').show();
                
                $('.impulse-column-gap-wrapper').show();
                $('.impulse-text-height-wrapper').show();
            }
        });

        $(document).on('click', '.impulse-add-pricing-plan', function() {
            var plans = [];
            try { plans = JSON.parse($('input[name="plans"]').val() || '[]'); } catch(e) {}
            if (plans.length >= 4) return;
            plans.push({
                title: 'New Plan',
                subtitle: 'Plan description',
                price: '29',
                currency: '$',
                period: '/month',
                yearly_price: '290',
                yearly_period: '/year',
                features: [{text:'Feature 1',status:'included'},{text:'Feature 2',status:'included'},{text:'Feature 3',status:'excluded'}],
                button_text: 'Get Started',
                button_link: '#',
                button_type: 'custom',
                ribbon: 'none',
                highlighted: false
            });
            $('input[name="plans"]').val(JSON.stringify(plans));
            rebuildPricingPlansList(plans);
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-remove-pricing-plan', function(e) {
            e.stopPropagation();
            var index = $(this).data('index');
            var plans = [];
            try { plans = JSON.parse($('input[name="plans"]').val() || '[]'); } catch(e) {}
            if (plans.length <= 1) return;
            plans.splice(index, 1);
            $('input[name="plans"]').val(JSON.stringify(plans));
            rebuildPricingPlansList(plans);
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-duplicate-pricing-plan', function(e) {
            e.stopPropagation();
            var index = $(this).data('index');
            var plans = [];
            try { plans = JSON.parse($('input[name="plans"]').val() || '[]'); } catch(e) {}
            if (plans.length >= 4) return;
            var clone = JSON.parse(JSON.stringify(plans[index]));
            clone.title = (clone.title || 'Plan') + ' Copy';
            plans.splice(index + 1, 0, clone);
            $('input[name="plans"]').val(JSON.stringify(plans));
            rebuildPricingPlansList(plans);
            autoSaveAndRefresh();
        });

        $(document).on('input', '.impulse-pricing-plan-title', function() {
            var index = $(this).data('index');
            var plans = [];
            try { plans = JSON.parse($('input[name="plans"]').val() || '[]'); } catch(e) {}
            if (plans[index]) {
                plans[index].title = $(this).val();
                $('input[name="plans"]').val(JSON.stringify(plans));
                autoSaveAndRefresh();
            }
        });

        $(document).on('click', '.impulse-edit-pricing-plan', function(e) {
            e.stopPropagation();
            var index = $(this).data('index');
            var plans = [];
            try { plans = JSON.parse($('input[name="plans"]').val() || '[]'); } catch(e) {}
            var plan = plans[index] || {};
            editingPricingPlanIndex = index;
            
            var features = plan.features || [];
            if (typeof features === 'string') {
                try { features = JSON.parse(features); } catch(e) { features = []; }
            }

            

            

            

            

            var modal = '<div class="impulse-pricing-modal" style="position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;background:#000;z-index:2147483647;display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity 0.15s ease-in-out">';
            modal += '<div class="impulse-pricing-modal-content" style="background:'+ImpC.surface+';border-radius:8px;width:480px;max-width:90%;max-height:85vh;overflow:auto;box-shadow:0 4px 20px rgba(0,0,0,0.4);color:'+ImpC.text+';opacity:0;transform:translateY(-10px);transition:opacity 0.15s ease-in-out,transform 0.15s ease-in-out">';
            modal += '<div style="padding:16px">';

            var checkColor = (typeof currentElementSettings !== 'undefined' && currentElementSettings.check_color) ? currentElementSettings.check_color : '#888888';
            var crossColor = (typeof currentElementSettings !== 'undefined' && currentElementSettings.cross_color) ? currentElementSettings.cross_color : '#888888';

            
            
            modal += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:5px;margin-bottom:5px">';
            modal += '<div><label style="display:block;font-size:11px;color:'+ImpC.muted+';margin-bottom:5px">Plan Name</label>';
            modal += '<input type="text" id="pricing-plan-title" value="' + (plan.title || '').replace(/"/g, '&quot;') + '" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
            modal += '<div><label style="display:block;font-size:11px;color:'+ImpC.muted+';margin-bottom:5px">Subtitle</label>';
            modal += '<input type="text" id="pricing-plan-subtitle" value="' + (plan.subtitle || '').replace(/"/g, '&quot;') + '" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box"></div>';
            modal += '</div>';

            

            
            modal += '<div style="font-weight:500;font-size:11px;color:#888;text-transform:uppercase;margin-bottom:5px;margin-top:5px">Pricing</div>';
            modal += '<div style="display:flex;gap:5px;margin-bottom:5px;align-items:center">';
            modal += '<input type="text" id="pricing-plan-currency" value="' + (plan.currency || '$').replace(/"/g, '&quot;') + '" placeholder="$" style="width:30px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;text-align:center;flex-shrink:0">';
            modal += '<input type="text" inputmode="decimal" id="pricing-plan-price" value="' + (plan.price || '').replace(/"/g, '&quot;') + '" placeholder="19" style="width:70px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;flex-shrink:0;text-align:right">';
            modal += '<input type="text" id="pricing-plan-period" value="' + (plan.period || '/month').replace(/"/g, '&quot;') + '" placeholder="/month" style="width:60px;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:#888;font-size:11px;box-sizing:border-box;flex-shrink:0">';
            modal += '<input type="text" inputmode="decimal" id="pricing-plan-yearly-price" value="' + (plan.yearly_price || '').replace(/"/g, '&quot;') + '" placeholder="190" style="width:70px;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;flex-shrink:0;text-align:right">';
            modal += '<input type="text" id="pricing-plan-yearly-period" value="' + (plan.yearly_period || '/year').replace(/"/g, '&quot;') + '" placeholder="/year" style="width:60px;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:#888;font-size:11px;box-sizing:border-box;flex-shrink:0">';
            modal += '</div>';

            modal += '<div style="font-weight:500;font-size:11px;color:#888;text-transform:uppercase;margin-bottom:5px">Ribbon</div>';
            modal += '<div style="display:flex;gap:5px;flex-wrap:wrap;margin-bottom:5px">';
            var ribbonOptions = [{v:'none',l:'None'},{v:'popular',l:'Popular'},{v:'sale',l:'Sale'},{v:'new',l:'New'},{v:'custom',l:'Custom'}];
            ribbonOptions.forEach(function(opt) {
                var isActive = (plan.ribbon || 'none') === opt.v;
                var checked = isActive ? 'background:'+ImpC.text+';color:'+ImpC.surface2+';border:1px solid '+ImpC.border+';' : 'background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';';
                modal += '<label style="height:26px;padding:0 10px;border-radius:3px;cursor:pointer;font-size:11px;display:inline-flex;align-items:center;box-sizing:border-box;' + checked + '">';
                modal += '<input type="radio" name="pricing-plan-ribbon" value="' + opt.v + '" ' + (isActive ? 'checked' : '') + ' style="display:none"> ' + opt.l + '</label>';
            });
            modal += '</div>';
            modal += '<div id="pricing-custom-ribbon-row" style="margin-bottom:5px;' + (plan.ribbon !== 'custom' ? 'display:none' : '') + '">';
            modal += '<input type="text" id="pricing-plan-ribbon-text" value="' + (plan.ribbon_text || 'Best Value').replace(/"/g, '&quot;') + '" placeholder="Custom ribbon text" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">';
            modal += '</div>';

            

            modal += '<label style="display:flex;align-items:center;gap:5px;margin-bottom:5px;cursor:pointer;color:'+ImpC.muted+';font-size:11px">';
            modal += '<input type="checkbox" id="pricing-plan-highlighted" class="impulse-checkbox" ' + (plan.highlighted ? 'checked' : '') + '>';
            modal += '<span>Highlight this plan</span></label>';

            modal += '<div style="font-weight:500;font-size:11px;color:#888;text-transform:uppercase;margin-bottom:5px;margin-top:5px">Features</div>';
            modal += '<div id="pricing-plan-features-list">';
            features.forEach(function(f, fi) {
                var fText = typeof f === 'string' ? f : (f.text || '');
                var fStatus = typeof f === 'string' ? 'included' : (f.status || 'included');
                modal += buildFeatureRow(fi, fText, fStatus, checkColor, crossColor);
            });
            modal += '</div>';
            modal += '<button type="button" id="pricing-add-feature-btn" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;margin-bottom:5px;color:'+ImpC.muted+';font-size:11px">+ Add Feature</button>';

            var btnType = plan.button_type || 'custom';
            var productName = plan.product_name || '';
            var pageLinkId = plan.page_id || '';
            var pageLinkName = '';
            if (btnType === 'page' && pageLinkId) {
                var _pg = (Impulse.pages || []).find(function(p) { return String(p.id) === String(pageLinkId); });
                if (_pg) pageLinkName = _pg.name;
            }
            
            modal += '<div style="display:flex;gap:5px;margin-bottom:5px;align-items:flex-end">';
            modal += '<div style="width:35%"><label style="display:block;font-size:11px;color:'+ImpC.muted+';margin-bottom:5px">Button</label>';
            modal += '<input type="text" id="pricing-plan-button-text" value="' + (plan.button_text || 'Get Started').replace(/"/g, '&quot;') + '" style="width:100%;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">';
            modal += '</div>';
            modal += '<div style="flex:1;min-width:0"><label style="display:block;font-size:11px;color:'+ImpC.muted+';margin-bottom:5px">Link</label>';
            modal += '<div class="impulse-btn-group pricing-link-type-group" data-name="pricing_link_type" style="display:flex;width:100%;gap:5px">';
            [{v:'custom',l:'URL'},{v:'page',l:'Page'},{v:'product',l:'Product'}].forEach(function(o) {
                var isActive = (btnType === o.v);

                

                var btnStyle = 'flex:1;height:26px;padding:0;font-size:11px;border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;box-sizing:border-box;'
                    + (isActive
                        ? 'background:'+ImpC.text+';color:'+ImpC.surface2+';border:1px solid '+ImpC.text+';font-weight:500;'
                        : 'background:'+ImpC.panel+';color:'+ImpC.muted+';border:1px solid '+ImpC.border+';');
                modal += '<button type="button" data-value="' + o.v + '"' + (isActive ? ' class="active"' : '') + ' style="' + btnStyle + '">' + o.l + '</button>';
            });
            modal += '<input type="hidden" name="pricing_link_type" value="' + btnType + '">';
            modal += '</div>';
            modal += '</div>';
            modal += '</div>';
            
            modal += '<div class="pricing-link-value-container" style="margin-bottom:5px">';
            if (btnType === 'custom') {
                modal += '<input type="text" id="pricing-plan-button-link" value="' + (plan.button_link || '#').replace(/"/g, '&quot;') + '" placeholder="https://..." style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">';
            } else if (btnType === 'page') {
                modal += '<select id="pricing-plan-page-id" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none;appearance:none;background-image:url(&quot;data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'8\' height=\'8\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%23999\' stroke-width=\'2\'%3E%3Cpath d=\'M6 9l6 6 6-6\'/%3E%3C/svg%3E&quot;);background-repeat:no-repeat;background-position:right 8px center">';
                modal += '<option value="">Select a page...</option>';
                (Impulse.pages || []).forEach(function(pg) {
                    modal += '<option value="' + pg.id + '"' + (String(pg.id) === String(pageLinkId) ? ' selected' : '') + '>' + pg.name + '</option>';
                });
                modal += '</select>';
            } else if (btnType === 'product') {
                modal += '<button type="button" class="pricing-pick-product-btn" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;color:' + (productName ? ''+ImpC.text+'' : ''+ImpC.muted+'') + ';box-sizing:border-box;display:flex;align-items:center;justify-content:center">' + (productName || 'Select a product...') + '</button>';
            }
            modal += '</div>';
            modal += '<input type="hidden" id="pricing-plan-button-type" value="' + btnType + '">';
            modal += '<input type="hidden" id="pricing-plan-button-link-val" value="' + (plan.button_link || '#').replace(/"/g, '&quot;') + '">';
            modal += '<input type="hidden" id="pricing-plan-product-id" value="' + (plan.product_id || '') + '">';
            modal += '<input type="hidden" id="pricing-plan-product-name" value="' + (productName).replace(/"/g, '&quot;') + '">';
            modal += '<input type="hidden" id="pricing-plan-page-id-val" value="' + pageLinkId + '">';
            
            modal += '</div>';
            modal += '<div style="padding:12px 16px;display:flex;justify-content:flex-end;gap:5px;background:'+ImpC.surface+'">';
            modal += '<button type="button" class="impulse-close-pricing-modal" style="height:26px;padding:0 16px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;color:'+ImpC.muted+';font-size:11px">Cancel</button>';
            modal += '<button type="button" class="impulse-save-pricing-plan" style="height:26px;padding:0 16px;background:'+ImpC.white+';color:'+ImpC.surface2+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;font-weight:500">Save</button>';
            modal += '</div></div></div>';

            
            document.documentElement.insertAdjacentHTML('beforeend', modal);

            
            
            try { upgradeCheckboxes(document.querySelector('.impulse-pricing-modal-content')); } catch(_e) {}

            
            
            setTimeout(function() {
                $('.impulse-pricing-modal').css('opacity', 1);
                $('.impulse-pricing-modal-content').css({opacity: 1, transform: 'translateY(0)'});
            }, 10);
        });
        
        function buildFeatureRow(index, text, status, checkColor, crossColor) {
            checkColor = checkColor || '#888888';
            crossColor = crossColor || '#888888';

            var isIncluded = status !== 'excluded';
            var checkSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
            var xSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
            
            var html = '<div class="pricing-feature-row" data-index="' + index + '" style="display:flex;gap:5px;align-items:center;margin-bottom:5px">';
            html += '<button type="button" class="pricing-feature-toggle" data-status="' + (isIncluded ? 'included' : 'excluded') + '" style="width:26px;height:26px;flex-shrink:0;border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box;background:' + (isIncluded ? ''+ImpC.panel+'' : ''+ImpC.surface+'') + ';color:' + (isIncluded ? checkColor : crossColor) + '">' + (isIncluded ? checkSvg : xSvg) + '</button>';
            html += '<input type="text" class="pricing-feature-text" value="' + (text || '').replace(/"/g, '&quot;') + '" placeholder="Feature description..." style="flex:1;height:26px;padding:0 8px;background:'+ImpC.surface+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
            html += '<button type="button" class="pricing-remove-feature" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
            html += '</div>';
            return html;
        }

        

        
        $(document).on('click', '.pricing-link-type-group button', function(e) {
            e.preventDefault();
            var type = $(this).data('value');
            var $group = $(this).closest('.pricing-link-type-group');
            $group.find('button').each(function() {
                $(this).removeClass('active')
                       .css('background', ImpC.panel)
                       .css('color', ImpC.muted)
                       .css('border', '1px solid ' + ImpC.border)
                       .css('font-weight', 'normal');
            });
            $(this).addClass('active')
                   .css('background', ImpC.text)
                   .css('color', ImpC.surface2)
                   .css('border', '1px solid ' + ImpC.text)
                   .css('font-weight', '500');
            $group.find('input[type="hidden"]').val(type);
            $('#pricing-plan-button-type').val(type);
            
            var $vc = $('.pricing-link-value-container');
            if (type === 'custom') {
                var url = $('#pricing-plan-button-link-val').val() || '#';
                $vc.html('<input type="text" id="pricing-plan-button-link" value="' + url.replace(/"/g, '&quot;') + '" placeholder="https://..." style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">');
            } else if (type === 'page') {
                var curPageId = $('#pricing-plan-page-id-val').val() || '';
                var html = '<select id="pricing-plan-page-id" style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none;appearance:none;background-image:url(&quot;data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'8\' height=\'8\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%23999\' stroke-width=\'2\'%3E%3Cpath d=\'M6 9l6 6 6-6\'/%3E%3C/svg%3E&quot;);background-repeat:no-repeat;background-position:right 8px center">';
                html += '<option value="">Select a page...</option>';
                (Impulse.pages || []).forEach(function(pg) {
                    html += '<option value="' + pg.id + '"' + (String(pg.id) === String(curPageId) ? ' selected' : '') + '>' + pg.name + '</option>';
                });
                html += '</select>';
                $vc.html(html);
            } else if (type === 'product') {
                var pName = $('#pricing-plan-product-name').val() || '';
                $vc.html('<button type="button" class="pricing-pick-product-btn" style="width:100%;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;font-size:11px;color:' + (pName ? ''+ImpC.text+'' : ''+ImpC.muted+'') + ';box-sizing:border-box;display:flex;align-items:center;justify-content:center">' + (pName || 'Select a product...') + '</button>');
            }
        });

        $(document).on('click', '.pricing-pick-product-btn', function(e) {
            e.preventDefault();
            openPricingProductModal();
        });

        $(document).on('click', '.pricing-product-item', function() {
            var id = $(this).data('id');
            var name = $(this).data('name');
            $('#pricing-plan-product-id').val(id);
            $('#pricing-plan-product-name').val(name);

            $('.pricing-pick-product-btn').text(name).css('color', ''+ImpC.text+'');
            
            $('.impulse-pricing-product-modal').remove();
        });

        $(document).on('blur', '#pricing-plan-button-link', function() {
            $('#pricing-plan-button-link-val').val($(this).val());
        });

        $(document).on('change', '#pricing-plan-page-id', function() {
            $('#pricing-plan-page-id-val').val($(this).val());
        });
        
        function openPricingProductModal() {
            
            $('.impulse-pricing-product-modal').remove();

            

            var productModal = '<div class="impulse-pricing-product-modal" style="position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0);z-index:2147483641;display:flex;align-items:center;justify-content:center;transition:background 0.15s ease-in-out">';
            productModal += '<div class="impulse-pricing-product-modal-content" style="background:'+ImpC.surface+';border-radius:8px;width:560px;max-width:90%;max-height:70vh;overflow:hidden;display:flex;flex-direction:column;box-shadow:0 4px 20px rgba(0,0,0,0.4);opacity:0;transform:translateY(-10px);transition:opacity 0.15s ease-in-out,transform 0.15s ease-in-out">';
            productModal += '<div style="padding:12px 16px;border-bottom:1px solid '+ImpC.border+';display:flex;justify-content:space-between;align-items:center">';
            productModal += '<div style="font-weight:500;font-size:14px;color:'+ImpC.white+'">Select Product</div>';
            productModal += '<button type="button" class="impulse-close-product-modal" style="background:none;border:none;font-size:18px;cursor:pointer;color:#666">&times;</button>';
            productModal += '</div>';
            productModal += '<div style="padding:12px 16px;border-bottom:1px solid '+ImpC.border+'">';
            productModal += '<input type="text" id="pricing-product-search" placeholder="Search products..." style="width:100%;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;box-sizing:border-box">';
            productModal += '</div>';
            productModal += '<div id="pricing-product-list" style="flex:1;overflow-y:auto;padding:12px;display:grid;grid-template-columns:repeat(4,1fr);gap:8px">';
            productModal += '<div style="grid-column:1/-1;text-align:center;padding:30px;color:#666">Loading products...</div>';
            productModal += '</div>';
            productModal += '</div></div>';
            
            $('body').append(productModal);

            setTimeout(function() {
                $('.impulse-pricing-product-modal').css('background', 'rgba(0,0,0,0.6)');
                $('.impulse-pricing-product-modal-content').css({opacity: 1, transform: 'translateY(0)'});
            }, 10);
            
            loadPricingProductList();
        }
        
        function loadPricingProductList(search) {
            $.get(Impulse.api + 'products', {
                search: search || '',
                per_page: 50,
                _wpnonce: Impulse.nonce
            }, function(response) {
                var products = response.data || response || [];
                if (!Array.isArray(products)) products = [];
                var html = '';
                products.forEach(function(p) {
                    var img = p.image_url || '';
                    if (!img && p.images) {
                        try {
                            var imgs = typeof p.images === 'string' ? JSON.parse(p.images) : p.images;
                            if (imgs && imgs[0] && imgs[0].url) img = imgs[0].url;
                        } catch(e) {}
                    }
                    html += '<div class="pricing-product-item" data-id="' + p.id + '" data-name="' + (p.name || '').replace(/"/g, '&quot;') + '" style="border:1px solid '+ImpC.border+';border-radius:3px;overflow:hidden;cursor:pointer;transition:border-color 0.15s;background:'+ImpC.panel+'">';
                    html += '<div style="aspect-ratio:1;background:'+ImpC.surface+';display:flex;align-items:center;justify-content:center;overflow:hidden">';
                    if (img) {
                        html += '<img src="' + img + '" alt="" style="width:100%;height:100%;object-fit:cover" onerror="this.style.display=\'none\';this.parentNode.innerHTML=\'No image\'">';
                    } else {
                        html += '<span style="color:#666;font-size:10px">No image</span>';
                    }
                    html += '</div>';
                    html += '<div style="padding:6px;font-size:10px;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:'+ImpC.text+'">' + (p.name || 'Untitled') + '</div>';
                    html += '</div>';
                });
                $('#pricing-product-list').html(html || '<div style="grid-column:1/-1;text-align:center;padding:30px;color:#666">No products found</div>');
            }).fail(function() {
                $('#pricing-product-list').html('<div style="grid-column:1/-1;text-align:center;padding:30px;color:#666">Failed to load products</div>');
            });
        }

        var pricingProductSearchTimer;
        $(document).on('input', '#pricing-product-search', function() {
            clearTimeout(pricingProductSearchTimer);
            var search = $(this).val();
            pricingProductSearchTimer = setTimeout(function() {
                loadPricingProductList(search);
            }, 300);
        });

        $(document).on('mouseenter', '.pricing-product-item', function() {
            $(this).css('border-color', ''+ImpC.white+'');
        }).on('mouseleave', '.pricing-product-item', function() {
            $(this).css('border-color', ''+ImpC.border+'');
        });

        $(document).on('click', '.impulse-close-product-modal', function() {
            $('.impulse-pricing-product-modal').remove();
        });
        $(document).on('click', '.impulse-pricing-product-modal', function(e) {
            if (e.target === this) {
                $(this).remove();
            }
        });

        $(document).on('change', 'input[name="pricing-plan-ribbon"]', function() {
            var val = $(this).val();
            $('input[name="pricing-plan-ribbon"]').closest('label').css({background:''+ImpC.panel+'',color:''+ImpC.muted+'',border:'1px solid '+ImpC.border+''});
            $(this).closest('label').css({background:''+ImpC.text+'',color:''+ImpC.surface2+'',border:'1px solid '+ImpC.border+''});
            if (val === 'custom') {
                $('#pricing-custom-ribbon-row').show();
            } else {
                $('#pricing-custom-ribbon-row').hide();
            }
        });

        $(document).on('click', '#pricing-add-feature-btn', function() {
            var $list = $('#pricing-plan-features-list');
            var count = $list.find('.pricing-feature-row').length;
            var checkColor = (typeof currentElementSettings !== 'undefined' && currentElementSettings.check_color) ? currentElementSettings.check_color : '#888888';
            var crossColor = (typeof currentElementSettings !== 'undefined' && currentElementSettings.cross_color) ? currentElementSettings.cross_color : '#888888';
            $list.append(buildFeatureRow(count, '', 'included', checkColor, crossColor));
        });

        $(document).on('click', '.pricing-remove-feature', function() {
            $(this).closest('.pricing-feature-row').remove();
        });

        $(document).on('click', '.pricing-feature-toggle', function() {
            var $btn = $(this);
            var current = $btn.data('status');
            var next = current === 'included' ? 'excluded' : 'included';
            $btn.data('status', next).attr('data-status', next);
            var checkSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
            var xSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
            if (next === 'included') {
                $btn.css({background:''+ImpC.panel+'',color:'#888'}).html(checkSvg);
            } else {
                $btn.css({background:''+ImpC.surface+'',color:'#888'}).html(xSvg);
            }
        });

        $(document).on('click', '.impulse-close-pricing-modal', function() {
            $('.impulse-pricing-modal').remove();
            editingPricingPlanIndex = -1;
        });
        $(document).on('click', '.impulse-pricing-modal', function(e) {
            if ($(e.target).hasClass('impulse-pricing-modal')) {
                $('.impulse-pricing-modal').remove();
                editingPricingPlanIndex = -1;
            }
        });

        $(document).on('click', '.impulse-save-pricing-plan', function() {
            var plans = [];
            try { plans = JSON.parse($('input[name="plans"]').val() || '[]'); } catch(e) {}

            var features = [];
            $('#pricing-plan-features-list .pricing-feature-row').each(function() {
                features.push({
                    text: $(this).find('.pricing-feature-text').val(),
                    status: $(this).find('.pricing-feature-toggle').data('status') || 'included'
                });
            });
            
            var ribbon = $('input[name="pricing-plan-ribbon"]:checked').val() || 'none';
            
            var updatedPlan = {
                title: $('#pricing-plan-title').val(),
                subtitle: $('#pricing-plan-subtitle').val(),
                currency: $('#pricing-plan-currency').val(),
                price: $('#pricing-plan-price').val(),
                period: $('#pricing-plan-period').val() || '/month',
                yearly_price: $('#pricing-plan-yearly-price').val(),
                yearly_period: $('#pricing-plan-yearly-period').val() || '/year',
                ribbon: ribbon,
                ribbon_text: ribbon === 'custom' ? $('#pricing-plan-ribbon-text').val() : '',
                highlighted: $('#pricing-plan-highlighted').is(':checked'),
                features: features,
                button_text: $('#pricing-plan-button-text').val(),
                button_type: $('#pricing-plan-button-type').val(),
                button_link: $('#pricing-plan-button-link').val() || $('#pricing-plan-button-link-val').val() || '#',
                page_id: $('#pricing-plan-page-id').val() || $('#pricing-plan-page-id-val').val() || '',
                product_id: $('#pricing-plan-product-id').val(),
                product_name: $('#pricing-plan-product-name').val()
            };
            
            if (editingPricingPlanIndex >= 0 && editingPricingPlanIndex < plans.length) {
                plans[editingPricingPlanIndex] = updatedPlan;
            }
            
            $('input[name="plans"]').val(JSON.stringify(plans));
            rebuildPricingPlansList(plans);
            autoSaveAndRefresh();
            
            $('.impulse-pricing-modal').remove();
            editingPricingPlanIndex = -1;
        });
        
        function rebuildPricingPlansList(plans) {
            var html = '';
            plans.forEach(function(plan, i) {
                html += '<div class="impulse-pricing-plan-item" data-index="' + i + '" style="margin-bottom:6px;display:flex;gap:5px;align-items:center">';
                html += '<input type="text" class="impulse-pricing-plan-title" data-index="' + i + '" value="' + (plan.title || 'Plan').replace(/"/g, '&quot;') + '" style="flex:1;height:26px;padding:0 8px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
                html += '<button type="button" class="impulse-edit-pricing-plan" data-index="' + i + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Edit"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg></button>';
                html += '<button type="button" class="impulse-duplicate-pricing-plan" data-index="' + i + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Duplicate"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button>';
                if (plans.length > 1) {
                    html += '<button type="button" class="impulse-remove-pricing-plan" data-index="' + i + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                }
                html += '</div>';
            });
            $('.impulse-pricing-plans-list').html(html);

            if (plans.length >= 4) {
                $('.impulse-add-pricing-plan').hide();
            } else {
                $('.impulse-add-pricing-plan').show();
            }
        }

        

        

        

        
        
        $(document).on('click', '.impulse-add-menu-item', function() {
            var items = [];
            try { items = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            items.push({label: 'New Link', url: '#'});
            $('input[name="items"]').val(JSON.stringify(items)).trigger('change');
            rebuildMenuEditor(items);
        });
        
        $(document).on('click', '.impulse-remove-menu-item', function() {
            var $item = $(this).closest('.impulse-menu-item');
            var index = $item.data('index');
            var items = [];
            try { items = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
            items.splice(index, 1);
            $('input[name="items"]').val(JSON.stringify(items)).trigger('change');
            rebuildMenuEditor(items);
        });
        
        $(document).on('change input', '.impulse-menu-label, .impulse-menu-url', function() {
            var items = [];
            $('.impulse-menu-item').each(function() {
                items.push({
                    label: $(this).find('.impulse-menu-label').val(),
                    url: $(this).find('.impulse-menu-url').val()
                });
            });
            $('input[name="items"]').val(JSON.stringify(items)).trigger('change');
        });

        $(document).on('change', 'input[name="source"]', function() {
            var source = $('input[name="source"]:checked').val();
            if (source === 'custom') {
                $('.impulse-nav-wp-menu').hide();
                $('.impulse-nav-custom').show();
            } else {
                $('.impulse-nav-wp-menu').show();
                $('.impulse-nav-custom').hide();
            }
        });
        
        function rebuildMenuEditor(items) {
            var html = '';
            items.forEach(function(item, i) {
                html += '<div class="impulse-menu-item" data-index="' + i + '" style="display:flex;gap:8px;align-items:center;margin-bottom:8px">';
                html += '<input type="text" class="impulse-menu-label" value="' + (item.label || '').replace(/"/g, '&quot;') + '" placeholder="Label" style="flex:1;padding:8px;border:1px solid #ddd;border-radius:4px">';
                html += '<input type="text" class="impulse-menu-url" value="' + (item.url || '').replace(/"/g, '&quot;') + '" placeholder="URL" style="flex:1;padding:8px;border:1px solid #ddd;border-radius:4px">';
                html += '<button type="button" class="impulse-remove-menu-item" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                html += '</div>';
            });
            $('.impulse-menu-editor').html(html);
        }

        

        
        var cellGridSettingsCache = {};

        function getCellGridRows() {
            var rows = [];
            try {
                rows = JSON.parse($('input[name="rows"]').val() || '[]');
            } catch(e) {}
            return rows;
        }

        function getLayoutGridColumns() {
            var cols = [];
            try {
                cols = JSON.parse($('input[name="columns"]').val() || '[]');
            } catch(e) {}
            return cols;
        }
        
        function saveLayoutGridColumns(cols, forceSyncSave) {
            $('input[name="columns"]').val(JSON.stringify(cols));
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            
            if (!cellGridSettingsCache[id]) cellGridSettingsCache[id] = {};
            cellGridSettingsCache[id].columns = cols;
            
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            var settings = collectSettingsFromPanel(existingSettings);
            var mergedSettings = $.extend({}, existingSettings, settings);
            
            cellGridSettingsCache[id] = $.extend({}, mergedSettings);
            if (typeof cellGridSettingsCache[id].columns === 'string') {
                try { cellGridSettingsCache[id].columns = JSON.parse(cellGridSettingsCache[id].columns); } catch(e) {}
            }
            
            $('.impulse-panel-right').data('existing-settings', mergedSettings);
            livePreviewSettings();
            
            clearTimeout(cellGridSaveTimer);
            if (forceSyncSave) {
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                    async: false
                });
                refreshPreview();
            } else {
                cellGridSaveTimer = setTimeout(function() {
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId })
                    });
                }, 300);
            }
        }

        var cellGridSaveTimer = null;
        function saveCellGridRows(rows, forceSyncSave) {
            $('input[name="rows"]').val(JSON.stringify(rows));

            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;

            if (!cellGridSettingsCache[id]) cellGridSettingsCache[id] = {};
            cellGridSettingsCache[id].rows = rows;

            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            var settings = collectSettingsFromPanel(existingSettings);
            var mergedSettings = $.extend({}, existingSettings, settings);

            cellGridSettingsCache[id] = $.extend({}, mergedSettings);
            if (typeof cellGridSettingsCache[id].rows === 'string') {
                try { cellGridSettingsCache[id].rows = JSON.parse(cellGridSettingsCache[id].rows); } catch(e) {}
            }

            $('.impulse-panel-right').data('existing-settings', mergedSettings);

            livePreviewSettings();

            clearTimeout(cellGridSaveTimer);
            
            if (forceSyncSave) {
                
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                    async: false
                });
                
                refreshPreview();
            } else {
                
                cellGridSaveTimer = setTimeout(function() {
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId })
                    });
                }, 300);
            }
        }

        function getCachedCellGridSettings(elementId) {
            return cellGridSettingsCache[elementId] || null;
        }

        function updateCellGridCache(elementId, settings) {
            if (!elementId) return;
            cellGridSettingsCache[elementId] = $.extend({}, settings);
            
            if (typeof cellGridSettingsCache[elementId].rows === 'string') {
                try { 
                    cellGridSettingsCache[elementId].rows = JSON.parse(cellGridSettingsCache[elementId].rows); 
                } catch(e) {}
            }
        }

        function getSelectedCellGridCells() {
            var cells = [];
            try {
                cells = JSON.parse($('input[name="_selected_cells"]').val() || '[]');
            } catch(e) {}
            return cells;
        }

        
        function withSelectedCellData(callback, forceSyncSave) {
            var isLayout = selectedElementType === 'columns';
            var isCellGrid = selectedElementType === 'rows';
            if (!isLayout && !isCellGrid) return false;

            var selected = getSelectedCellGridCells();
            if (selected.length !== 1) return false;

            var parts = selected[0].split('-');
            var cellData, container, rowIdxL, colIdxL;

            if (isLayout) {
                colIdxL = parseInt(parts[0]);
                rowIdxL = parseInt(parts[1]);
                container = getLayoutGridColumns();
                cellData = (container[colIdxL] && container[colIdxL].cells[rowIdxL]) ? container[colIdxL].cells[rowIdxL] : null;
            } else {
                rowIdxL = parseInt(parts[0]);
                colIdxL = parseInt(parts[1]);
                container = getCellGridRows();
                cellData = (container[rowIdxL] && container[rowIdxL].cells[colIdxL]) ? container[rowIdxL].cells[colIdxL] : null;
            }

            if (!cellData) return false;

            

            
            
            if (Array.isArray(cellData)) {
                cellData = {};
                if (isLayout) container[colIdxL].cells[rowIdxL] = cellData;
                else          container[rowIdxL].cells[colIdxL] = cellData;
            }

            callback(cellData);
            
            if (isLayout) {
                saveLayoutGridColumns(container, forceSyncSave || false);
            } else {
                saveCellGridRows(container, forceSyncSave || false);
            }
            return true;
        }

        var RESPONSIVE_CELL_KEYS = ['padding_sides', 'padding_top', 'padding_bottom', 'valign', 'halign'];

        function getCellDeviceVal(cellData, key, defaultVal) {
            var device = window.impulseDevice || 'desktop';
            if (device === 'mobile') {
                if (cellData[key + '_mobile'] !== undefined) return cellData[key + '_mobile'];
                if (cellData[key + '_tablet'] !== undefined) return cellData[key + '_tablet'];
            } else if (device === 'tablet') {
                if (cellData[key + '_tablet'] !== undefined) return cellData[key + '_tablet'];
            }
            return cellData[key] !== undefined ? cellData[key] : defaultVal;
        }

        function setCellDeviceVal(cellData, key, val) {
            var device = window.impulseDevice || 'desktop';
            if (RESPONSIVE_CELL_KEYS.indexOf(key) !== -1 && device !== 'desktop') {
                cellData[key + '_' + device] = val;
            } else {
                cellData[key] = val;
            }
        }

        function refreshCellGridPanel() {
            var id = $('.impulse-panel-right').data('element-id');
            if (id && (selectedElementType === 'rows' || selectedElementType === 'columns')) {
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    success: function(resp) {
                        if (resp && resp.id) {
                            openSettings(resp.id, selectedElementType);
                        }
                    }
                });
            }
        }

            var gridSelectorRowCols = []; 

            function initGridSelectorFromRows() {
                if (selectedElementType === 'columns') {
                    var cols = getLayoutGridColumns();
                    
                    gridSelectorRowCols = cols.map(function(c) { return c.cells.length; });
                } else {
                    var rows = getCellGridRows();
                    gridSelectorRowCols = rows.map(function(r) { return r.widths.length; });
                }
            }

            function updateGridSelectorVisual() {
                if (selectedElementType === 'columns') {

                    $('.impulse-grid-selector-cell').each(function() {
                        var gc = parseInt($(this).data('col'));
                        var gr = parseInt($(this).data('row'));
                        var isActive = gc < gridSelectorRowCols.length && gr < gridSelectorRowCols[gc];
                        $(this).toggleClass('active', isActive);
                        $(this).toggleClass('hover-active', false);
                    });
                } else {
                    
                    $('.impulse-grid-selector-cell').each(function() {
                        var c = parseInt($(this).data('col'));
                        var r = parseInt($(this).data('row'));
                        var isActive = r < gridSelectorRowCols.length && c < gridSelectorRowCols[r];
                        $(this).toggleClass('active', isActive);
                        $(this).toggleClass('hover-active', false);
                    });
                }
            }

            $(document).on('mouseenter', '.impulse-grid-selector-cell', function() {
                if (selectedElementType !== 'rows' && selectedElementType !== 'columns') return;
                var hoverCol = parseInt($(this).data('col'));
                var hoverRow = parseInt($(this).data('row'));
                
                if (selectedElementType === 'columns') {
                    
                    $('.impulse-grid-selector-cell').each(function() {
                        var c = parseInt($(this).data('col'));
                        var r = parseInt($(this).data('row'));
                        if (c === hoverCol && r <= hoverRow) {
                            $(this).addClass('hover-active');
                        } else {
                            $(this).removeClass('hover-active');
                        }
                    });
                    var previewCols = gridSelectorRowCols.slice();
                    while (previewCols.length <= hoverCol) previewCols.push(0);
                    previewCols[hoverCol] = hoverRow + 1;
                    while (previewCols.length > 0 && previewCols[previewCols.length - 1] === 0) previewCols.pop();
                } else {
                    
                    $('.impulse-grid-selector-cell').each(function() {
                        var c = parseInt($(this).data('col'));
                        var r = parseInt($(this).data('row'));
                        if (r === hoverRow && c <= hoverCol) {
                            $(this).addClass('hover-active');
                        } else {
                            $(this).removeClass('hover-active');
                        }
                    });
                    
                    var previewCols = gridSelectorRowCols.slice();
                    while (previewCols.length <= hoverRow) previewCols.push(0);
                    previewCols[hoverRow] = hoverCol + 1;
                    while (previewCols.length > 0 && previewCols[previewCols.length - 1] === 0) previewCols.pop();
                }
            });
            
            $(document).on('mouseleave', '.impulse-grid-selector', function() {
                if (selectedElementType !== 'rows' && selectedElementType !== 'columns') return;
                $('.impulse-grid-selector-cell').removeClass('hover-active');
                initGridSelectorFromRows();
                updateGridSelectorVisual();
            });

            $(document).on('click', '.impulse-grid-selector-cell', function(e) {
                if (selectedElementType !== 'rows' && selectedElementType !== 'columns') return;
                
                var $cell = $(this);
                var clickedCol = parseInt($cell.data('col'));
                var clickedRow = parseInt($cell.data('row'));
                var isActive = $cell.hasClass('active');
                var isLayoutGrid = selectedElementType === 'columns';

                if (isActive) {
                    e.preventDefault();
                    e.stopPropagation();

                    var cellKey = isLayoutGrid ? (clickedCol + '-' + clickedRow) : (clickedRow + '-' + clickedCol);
                    var elementId = $('.impulse-panel-right').data('element-id');
                    
                    var currentSelection = [];
                    try {
                        currentSelection = JSON.parse($('input[name="_selected_cells"]').val() || '[]');
                    } catch(ex) {}
                    
                    var newSelection;
                    if (e.shiftKey) {
                        var idx = currentSelection.indexOf(cellKey);
                        if (idx > -1) {
                            currentSelection.splice(idx, 1);
                            newSelection = currentSelection;
                        } else {
                            newSelection = currentSelection.concat([cellKey]);
                        }
                    } else {
                        if (currentSelection.length === 1 && currentSelection[0] === cellKey) {
                            newSelection = [];
                        } else {
                            newSelection = [cellKey];
                        }
                    }
                    
                    $('input[name="_selected_cells"]').val(JSON.stringify(newSelection));

                    $('.impulse-grid-selector-cell').removeClass('selected');
                    newSelection.forEach(function(key) {
                        var parts = key.split('-');
                        if (isLayoutGrid) {
                            $('.impulse-grid-selector-cell[data-col="' + parts[0] + '"][data-row="' + parts[1] + '"]').addClass('selected');
                        } else {
                            $('.impulse-grid-selector-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]').addClass('selected');
                        }
                    });
                    
                    var currentSettings = {};
                    $('.impulse-panel-right input, .impulse-panel-right select, .impulse-panel-right textarea').each(function() {
                        var name = $(this).attr('name');
                        if (!name) return;
                        currentSettings[name] = $(this).is(':checkbox') ? $(this).is(':checked') : $(this).val();
                    });
                    currentSettings._selected_cells = newSelection;
                    
                    if (typeof currentSettings.rows === 'string') {
                        try { currentSettings.rows = JSON.parse(currentSettings.rows); } catch(e) {}
                    }
                    if (typeof currentSettings.columns === 'string') {
                        try { currentSettings.columns = JSON.parse(currentSettings.columns); } catch(e) {}
                    }
                    
                    updateCellGridCache(elementId, currentSettings);
                    $('.impulse-panel-right').data('existing-settings', currentSettings);
                    var children = $('.impulse-panel-right').data('cell-grid-children') || [];
                    
                    var html = buildSettingsForm(selectedElementType, currentSettings, children);
                    $('#impulse-settings-body').html(html);
                    $('.impulse-panel-right').data('element-id', elementId);
                    
                    initGridSelectorFromRows();
                    updateGridSelectorVisual();

                    $('.impulse-grid-selector-cell').removeClass('selected');
                    newSelection.forEach(function(key) {
                        var parts = key.split('-');
                        if (isLayoutGrid) {
                            $('.impulse-grid-selector-cell[data-col="' + parts[0] + '"][data-row="' + parts[1] + '"]').addClass('selected');
                        } else {
                            $('.impulse-grid-selector-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]').addClass('selected');
                        }
                    });
                    
                    livePreviewSettings(elementId, selectedElementType);

                    try {
                        var iframe = document.getElementById('impulse-iframe');
                        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        var cellClass = isLayoutGrid ? '.impulse-layout-cell' : '.impulse-rows-cell';
                        iframeDoc.querySelectorAll(cellClass).forEach(function(c) { c.classList.remove('selected'); });
                        newSelection.forEach(function(key) {
                            var parts = key.split('-');
                            var cell;
                            if (isLayoutGrid) {
                                cell = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"] .impulse-layout-cell[data-col="' + parts[0] + '"][data-row="' + parts[1] + '"]');
                            } else {
                                cell = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"] .impulse-rows-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]');
                            }
                            if (cell) cell.classList.add('selected');
                        });
                    } catch(ex) {}
                    
                    return false;
                }

                if (isLayoutGrid) {
                    
                    var newCellCount = clickedRow + 1;
                    var currentCols = getLayoutGridColumns();

                    while (currentCols.length <= clickedCol) {
                        currentCols.push({ width: 100 / (currentCols.length + 1), cells: [{}] });
                    }
                    
                    var colWidth = 100 / currentCols.length;
                    currentCols.forEach(function(c) { c.width = colWidth; });

                    if (currentCols[clickedCol] && currentCols[clickedCol].cells.length === newCellCount) {
                        if (newCellCount === 1 && clickedCol === currentCols.length - 1 && currentCols.length > 1) {
                            currentCols.pop();
                            colWidth = 100 / currentCols.length;
                            currentCols.forEach(function(c) { c.width = colWidth; });
                        }
                    } else {
                        var existingCells = currentCols[clickedCol] ? currentCols[clickedCol].cells.slice() : [];
                        while (existingCells.length < newCellCount) existingCells.push({});
                        existingCells = existingCells.slice(0, newCellCount);
                        currentCols[clickedCol].cells = existingCells;
                    }

                    while (currentCols.length > 1 && currentCols[currentCols.length - 1].cells.length === 0) {
                        currentCols.pop();
                    }
                    
                    gridSelectorRowCols = currentCols.map(function(c) { return c.cells.length; });
                    updateGridSelectorVisual();
                    saveLayoutGridColumns(currentCols, true);
                    refreshPreview();
                } else {
                    
                    var newColCount = clickedCol + 1;
                    var currentRows = getCellGridRows();
                    
                    while (currentRows.length <= clickedRow) {
                        var defaultCols = currentRows.length > 0 ? currentRows[0].widths.length : 3;
                        var widths = [];
                        var cells = [];
                        for (var i = 0; i < defaultCols; i++) {
                            widths.push(100 / defaultCols);
                            cells.push({});
                        }
                        currentRows.push({ widths: widths, cells: cells });
                    }
                    
                    if (currentRows[clickedRow] && currentRows[clickedRow].widths.length === newColCount) {
                        if (newColCount === 1 && clickedRow === currentRows.length - 1 && currentRows.length > 1) {
                            currentRows.pop();
                        }
                    } else {
                        var cellWidth = 100 / newColCount;
                        var newWidths = [];
                        var newCells = currentRows[clickedRow] ? currentRows[clickedRow].cells.slice() : [];
                        for (var c = 0; c < newColCount; c++) {
                            newWidths.push(cellWidth);
                            if (!newCells[c]) newCells[c] = {};
                        }
                        newCells = newCells.slice(0, newColCount);
                        currentRows[clickedRow] = { widths: newWidths, cells: newCells };
                    }
                    
                    while (currentRows.length > 1 && currentRows[currentRows.length - 1].widths.length === 0) {
                        currentRows.pop();
                    }
                    
                    gridSelectorRowCols = currentRows.map(function(r) { return r.widths.length; });
                    updateGridSelectorVisual();
                    saveCellGridRows(currentRows, true);
                    refreshPreview();
                }
            });

        
        
        function rebuildLayoutGridPanel(elementId, settings, selectedCells) {
            settings._selected_cells = selectedCells || [];
            if (typeof settings.columns === 'string') {
                try { settings.columns = JSON.parse(settings.columns); } catch(e) {}
            }
            updateCellGridCache(elementId, settings);
            $('.impulse-panel-right').data('existing-settings', settings);
            var children = $('.impulse-panel-right').data('cell-grid-children') || [];
            var html = buildSettingsForm('columns', settings, children);
            $('#impulse-settings-body').html(html);
            $('.impulse-panel-right').data('element-id', elementId);
        }

        $(document).on('click', '.impulse-lg-cell', function(e) {
            if ($(e.target).hasClass('lg-cell-remove')) return;
            if (selectedElementType !== 'columns') return;
            
            var colIdx = parseInt($(this).data('col'));
            var rowIdx = parseInt($(this).data('row'));
            var cellKey = colIdx + '-' + rowIdx;
            var elementId = $('.impulse-panel-right').data('element-id');
            
            var currentSelection = [];
            try { currentSelection = JSON.parse($('input[name="_selected_cells"]').val() || '[]'); } catch(ex) {}
            
            var newSelection;
            if (currentSelection.length === 1 && currentSelection[0] === cellKey) {
                newSelection = []; 
            } else {
                newSelection = [cellKey];
            }

            var currentSettings = {};
            $('.impulse-panel-right input, .impulse-panel-right select, .impulse-panel-right textarea').each(function() {
                var name = $(this).attr('name');
                if (!name) return;
                currentSettings[name] = $(this).val();
            });
            currentSettings._selected_cells = newSelection;
            if (typeof currentSettings.columns === 'string') {
                try { currentSettings.columns = JSON.parse(currentSettings.columns); } catch(e) {}
            }
            
            rebuildLayoutGridPanel(elementId, currentSettings, newSelection);

            try {
                var iframe = document.getElementById('impulse-iframe');
                var iframeDoc = iframe.contentDocument;
                iframeDoc.querySelectorAll('.impulse-layout-cell').forEach(function(c) { c.classList.remove('selected'); });
                newSelection.forEach(function(key) {
                    var parts = key.split('-');
                    var cell = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"] .impulse-layout-cell[data-col="' + parts[0] + '"][data-row="' + parts[1] + '"]');
                    if (cell) cell.classList.add('selected');
                });
            } catch(ex) {}
            
            livePreviewSettings(elementId, 'columns');
        });

        $(document).on('click', '.impulse-lg-add-col', function() {
            if (selectedElementType !== 'columns') return;
            var cols = getLayoutGridColumns();
            if (cols.length >= 6) return;
            
            var newWidth = 100 / (cols.length + 1);
            cols.forEach(function(c) { c.width = newWidth; });
            cols.push({ width: newWidth, cells: [{}] });
            
            saveLayoutGridColumns(cols, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.columns = cols;
            rebuildLayoutGridPanel(elementId, settings, []);
        });

        $(document).on('click', '.impulse-lg-col-remove', function(e) {
            e.stopPropagation();
            if (selectedElementType !== 'columns') return;
            var colIdx = parseInt($(this).data('col'));
            var cols = getLayoutGridColumns();
            if (cols.length <= 1) return;
            
            cols.splice(colIdx, 1);
            var newWidth = 100 / cols.length;
            cols.forEach(function(c) { c.width = newWidth; });
            
            saveLayoutGridColumns(cols, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.columns = cols;
            rebuildLayoutGridPanel(elementId, settings, []);
        });

        $(document).on('click', '.impulse-lg-add-cell', function() {
            if (selectedElementType !== 'columns') return;
            var colIdx = parseInt($(this).data('col'));
            var cols = getLayoutGridColumns();
            if (!cols[colIdx]) return;
            if (cols[colIdx].cells.length >= 6) return;
            
            cols[colIdx].cells.push({});
            
            saveLayoutGridColumns(cols, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.columns = cols;
            rebuildLayoutGridPanel(elementId, settings, []);
        });

        $(document).on('click', '.lg-cell-remove', function(e) {
            e.stopPropagation();
            if (selectedElementType !== 'columns') return;
            var colIdx = parseInt($(this).data('col'));
            var rowIdx = parseInt($(this).data('row'));
            var cols = getLayoutGridColumns();
            if (!cols[colIdx] || cols[colIdx].cells.length <= 1) return;
            
            cols[colIdx].cells.splice(rowIdx, 1);
            
            saveLayoutGridColumns(cols, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.columns = cols;
            rebuildLayoutGridPanel(elementId, settings, []);
        });

        

        
        var _lgPctDrag = null, _lgPctSuppressClick = false;

        $(document).on('click', '.lg-col-pct', function(e) {
            if (selectedElementType !== 'columns') return;
            e.stopPropagation();
            if (_lgPctSuppressClick) { _lgPctSuppressClick = false; return; }
            var range = document.createRange();
            range.selectNodeContents(this);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        });

        $(document).on('keydown', '.lg-col-pct', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.blur();
            }
        });

        
        if (!window._impulseLgLocks) window._impulseLgLocks = {};
        function _lgLockKey() {
            return $('.impulse-panel-right').data('element-id') || 'unknown';
        }
        function _lgGetLock() {
            var k = _lgLockKey();
            if (!window._impulseLgLocks[k]) window._impulseLgLocks[k] = { edited: {} };
            return window._impulseLgLocks[k];
        }
        function _lgClearLock() {
            delete window._impulseLgLocks[_lgLockKey()];
        }
        $(document).on('focusout.lgPctLock', '.impulse-lg-pcts > .lg-col-pct', function() {
            setTimeout(function() {
                if ($('.impulse-lg-pcts > .lg-col-pct:focus').length === 0) {
                    _lgClearLock();
                }
            }, 0);
        });

        $(document).on('blur', '.lg-col-pct', function() {
            if (_lgPctDrag && _lgPctDrag.moved) return; 
            var $span = $(this);
            var colIdx = parseInt($span.attr('data-col'));
            var newVal = parseInt(($span.text() || '').replace(/[^\d]/g, ''));
            var cols = getLayoutGridColumns();
            if (!cols || !cols.length) return;
            var n = cols.length;

            if (n === 1) { cols[0].width = 100; $span.text(100); return; }
            if (isNaN(newVal) || newVal < 1) {
                $span.text(Math.round((cols[colIdx] && cols[colIdx].width) || 0));
                return;
            }

            var $editor = $span.closest('.impulse-lg-editor');
            var st = _lgGetLock();

            
            var candidates = [];
            for (var c = 1; c < n; c++) {
                var idx = (colIdx + c) % n;
                if (idx === colIdx) continue;
                if (!st.edited[idx]) candidates.push(idx);
            }

            
            var lockedOtherSum = 0, lockedOtherCount = 0;
            for (var i = 0; i < n; i++) {
                if (i === colIdx || !st.edited[i]) continue;
                lockedOtherSum += cols[i].width;
                lockedOtherCount++;
            }
            var unlockedOtherCount = (n - 1) - lockedOtherCount;
            var maxAllowed = 100 - lockedOtherSum - unlockedOtherCount;
            if (maxAllowed < 1) maxAllowed = 1;
            if (newVal > maxAllowed) newVal = maxAllowed;

            st.edited[colIdx] = true;

            var delta = cols[colIdx].width - newVal;
            cols[colIdx].width = newVal;

            var ci = 0;
            while (delta !== 0 && ci < candidates.length) {
                var ac = candidates[ci];
                if (delta > 0) {
                    cols[ac].width += delta;
                    delta = 0;
                } else {
                    var room = cols[ac].width - 1;
                    if (room <= 0) { ci++; continue; }
                    var take = Math.min(-delta, room);
                    cols[ac].width -= take;
                    delta += take;
                    if (delta < 0) ci++;
                }
            }
            if (delta !== 0) {
                cols[colIdx].width -= delta;
                if (cols[colIdx].width < 1) cols[colIdx].width = 1;
            }

            for (var k = 0; k < n; k++) cols[k].width = Math.round(cols[k].width);
            var total = 0;
            for (var k2 = 0; k2 < n; k2++) total += cols[k2].width;
            if (total !== 100) {
                var diff = 100 - total;
                var landed = false;
                for (var m = 0; m < n; m++) {
                    var idx2 = (colIdx + 1 + m) % n;
                    if (idx2 === colIdx) continue;
                    if (st.edited[idx2]) continue;
                    if (cols[idx2].width + diff >= 1) { cols[idx2].width += diff; landed = true; break; }
                }
                if (!landed) {
                    cols[colIdx].width += diff;
                    if (cols[colIdx].width < 1) cols[colIdx].width = 1;
                }
            }

            for (var p = 0; p < n; p++) {
                $editor.find('.impulse-lg-editor-cols > .impulse-lg-col[data-col="' + p + '"]').css('flex', cols[p].width);
                $editor.find('.impulse-lg-pcts > .lg-col-pct[data-col="' + p + '"]').text(cols[p].width);
            }
            $span.text(cols[colIdx].width);
            $('input[name="columns"]').val(JSON.stringify(cols));
            saveLayoutGridColumns(cols, false);
        });

        

        $(document).on('mousedown', '.lg-col-pct', function(e) {
            if (selectedElementType !== 'columns' || e.which !== 1) return;
            var $span = $(this);
            var colIdx = parseInt($span.attr('data-col'));
            var cols = getLayoutGridColumns();
            if (!cols || cols.length < 2) return; 
            _lgPctDrag = {
                colIdx: colIdx, startX: e.clientX,
                startVal: parseInt(cols[colIdx] && cols[colIdx].width) || 0,
                moved: false, cols: cols,
                $editor: $span.closest('.impulse-lg-editor')
            };
        });
        $(document).on('mousemove.lgPctDrag', function(e) {
            var d = _lgPctDrag; if (!d) return;
            var dx = e.clientX - d.startX;
            if (!d.moved) {
                if (Math.abs(dx) < 3) return;
                d.moved = true;
                if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
                document.body.style.cursor = 'ew-resize';
            }
            e.preventDefault();
            var cols = d.cols, n = cols.length;
            var nb = (d.colIdx < n - 1) ? d.colIdx + 1 : d.colIdx - 1; 
            var pair = cols[d.colIdx].width + cols[nb].width;
            var newVal = d.startVal + Math.round(dx / 3); 
            newVal = Math.max(1, Math.min(pair - 1, newVal));
            cols[d.colIdx].width = newVal;
            cols[nb].width = pair - newVal;
            for (var p = 0; p < n; p++) {
                d.$editor.find('.impulse-lg-editor-cols > .impulse-lg-col[data-col="' + p + '"]').css('flex', cols[p].width);
                d.$editor.find('.impulse-lg-pcts > .lg-col-pct[data-col="' + p + '"]').css('flex', cols[p].width).text(cols[p].width);
            }
            $('input[name="columns"]').val(JSON.stringify(cols));
        });
        $(document).on('mouseup.lgPctDrag', function() {
            var d = _lgPctDrag; if (!d) return;
            if (d.moved) {
                document.body.style.cursor = '';
                _lgPctSuppressClick = true;
                saveLayoutGridColumns(d.cols, true);
            }
            _lgPctDrag = null;
        });

        var lgDragState = { isDragging: false, fromCol: null, fromRow: null };
        
        $(document).on('dragstart', '.impulse-lg-cell.has-content', function(e) {
            if (selectedElementType !== 'columns') return;
            lgDragState.isDragging = true;
            lgDragState.fromCol = parseInt($(this).data('col'));
            lgDragState.fromRow = parseInt($(this).data('row'));
            $(this).addClass('dragging');
            e.originalEvent.dataTransfer.effectAllowed = 'move';
            e.originalEvent.dataTransfer.setData('text/plain', lgDragState.fromCol + '-' + lgDragState.fromRow);
        });
        
        $(document).on('dragover', '.impulse-lg-cell', function(e) {
            if (!lgDragState.isDragging || selectedElementType !== 'columns') return;
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'move';
            $('.impulse-lg-cell').removeClass('drag-over');
            $(this).addClass('drag-over');
        });
        
        $(document).on('dragleave', '.impulse-lg-cell', function() {
            $(this).removeClass('drag-over');
        });
        
        $(document).on('drop', '.impulse-lg-cell', function(e) {
            e.preventDefault();
            if (!lgDragState.isDragging || selectedElementType !== 'columns') return;
            
            var toCol = parseInt($(this).data('col'));
            var toRow = parseInt($(this).data('row'));
            var fromCol = lgDragState.fromCol;
            var fromRow = lgDragState.fromRow;
            
            if (fromCol === toCol && fromRow === toRow) {
                lgDragState.isDragging = false;
                $('.impulse-lg-cell').removeClass('dragging drag-over');
                return;
            }
            
            var elementId = $('.impulse-panel-right').data('element-id');
            
            $.ajax({
                url: Impulse.api + 'elements/' + elementId + '/swap-cells',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({
                    from_row: fromRow,
                    from_col: fromCol,
                    to_row: toRow,
                    to_col: toCol,
                    element_type: 'columns'
                }),
                success: function() {
                    refreshPreview();
                    openSettings(elementId, 'columns');
                }
            });
            
            lgDragState.isDragging = false;
            $('.impulse-lg-cell').removeClass('dragging drag-over');
        });
        
        $(document).on('dragend', '.impulse-lg-cell', function() {
            lgDragState.isDragging = false;
            $('.impulse-lg-cell').removeClass('dragging drag-over');
        });

        var cellGridDragState = {
            isDragging: false,
            fromRow: null,
            fromCol: null
        };
        
        function initCellGridDragDrop() {
            
            $(document).off('dragstart.cellgrid').on('dragstart.cellgrid', '.impulse-cg-cell.has-content, .impulse-grid-selector-cell.has-content', function(e) {
                var $cell = $(this);
                cellGridDragState.isDragging = true;
                cellGridDragState.fromRow = parseInt($cell.data('row'));
                cellGridDragState.fromCol = parseInt($cell.data('col'));
                
                $cell.addClass('dragging');

                e.originalEvent.dataTransfer.effectAllowed = 'move';
                e.originalEvent.dataTransfer.setData('text/plain', cellGridDragState.fromRow + '-' + cellGridDragState.fromCol);
            });

            $(document).off('dragover.cellgrid').on('dragover.cellgrid', '.impulse-cg-cell, .impulse-grid-selector-cell.active', function(e) {
                if (!cellGridDragState.isDragging) return;
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'move';

                $('.impulse-cg-cell, .impulse-grid-selector-cell').removeClass('drag-over');
                $(this).addClass('drag-over');
            });

            $(document).off('dragleave.cellgrid').on('dragleave.cellgrid', '.impulse-cg-cell, .impulse-grid-selector-cell', function(e) {
                $(this).removeClass('drag-over');
            });

            $(document).off('drop.cellgrid').on('drop.cellgrid', '.impulse-cg-cell, .impulse-grid-selector-cell.active', function(e) {
                e.preventDefault();
                
                if (!cellGridDragState.isDragging) return;
                
                var $target = $(this);
                var toRow = parseInt($target.data('row'));
                var toCol = parseInt($target.data('col'));

                $('.impulse-cg-cell, .impulse-grid-selector-cell').removeClass('dragging drag-over');

                if (toRow === cellGridDragState.fromRow && toCol === cellGridDragState.fromCol) {
                    cellGridDragState.isDragging = false;
                    return;
                }

                var id = $('.impulse-panel-right').data('element-id');
                var isLayout = selectedElementType === 'columns';
                if (id) {

                    
                    
                    var postData;
                    if (isLayout) {

                        postData = {
                            element_type: 'columns',
                            from_col: cellGridDragState.fromCol,
                            from_row: cellGridDragState.fromRow,
                            to_col: toCol,
                            to_row: toRow
                        };
                    } else {
                        postData = {
                            element_type: 'rows',
                            from_row: cellGridDragState.fromRow,
                            from_col: cellGridDragState.fromCol,
                            to_row: toRow,
                            to_col: toCol
                        };
                    }
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + id + '/swap-cells',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify(postData),
                        success: function(resp) {
                            
                            refreshPreview();
                            
                            setTimeout(function() {
                                openSettings(id, selectedElementType);
                            }, 300);
                        },
                        error: function(xhr, status, error) {
                            console.error('Cell swap failed:', error);
                        }
                    });
                }
                
                cellGridDragState.isDragging = false;
            });

            $(document).off('dragend.cellgrid').on('dragend.cellgrid', '.impulse-cg-cell, .impulse-grid-selector-cell', function(e) {
                $('.impulse-cg-cell, .impulse-grid-selector-cell').removeClass('dragging drag-over');
                cellGridDragState.isDragging = false;
            });
        }

        

        
        function rebuildCellGridEditorPanel(elementId, settings, selectedCells) {
            settings._selected_cells = selectedCells || [];
            if (typeof settings.rows === 'string') {
                try { settings.rows = JSON.parse(settings.rows); } catch(e) {}
            }
            updateCellGridCache(elementId, settings);
            $('.impulse-panel-right').data('existing-settings', settings);
            var children = $('.impulse-panel-right').data('cell-grid-children') || [];
            var html = buildSettingsForm('rows', settings, children);
            $('#impulse-settings-body').html(html);
            $('.impulse-panel-right').data('element-id', elementId);
        }

        
        
        $(document).on('contextmenu', '.impulse-cg-cell', function(e) {
            if (selectedElementType !== 'rows') return;
            e.preventDefault(); e.stopPropagation();
            var row = parseInt($(this).data('row'));
            var col = parseInt($(this).data('col'));
            var settings2 = $('.impulse-panel-right').data('existing-settings') || {};
            var rowsData = settings2.rows || [];
            if (typeof rowsData === 'string') { try { rowsData = JSON.parse(rowsData); } catch(e2) { rowsData = []; } }
            var rowCellCount = (rowsData[row] && rowsData[row].widths) ? rowsData[row].widths.length : 1;
            var rowCount = rowsData.length || 1;
            window._cgCtxRow = row; window._cgCtxCol = col;
            var h = '';
            h += window.ctxItem('cg-add-cell',    'Add cell');
            if (rowCellCount > 1) h += window.ctxItem('cg-remove-cell', 'Remove cell', '', 'danger');
            h += window.ctxDiv();
            h += window.ctxItem('cg-add-row-above', 'Add row above');
            h += window.ctxItem('cg-add-row-below', 'Add row below');
            if (rowCount > 1) h += window.ctxItem('cg-remove-row',  'Remove row', '', 'danger');
            window.ctxShow($('#impulse-context-menu'), e.clientX, e.clientY, h);
        });

        $(document).on('click', '#impulse-context-menu .impulse-context-item', function() {
            var action = $(this).data('action');
            if (!action || !action.startsWith('cg-')) return;
            window.ctxHide();
            var row = window._cgCtxRow, col = window._cgCtxCol;
            if (action === 'cg-add-cell') {
                $('.impulse-cg-add-cell[data-row="' + row + '"]').trigger('click');
            } else if (action === 'cg-remove-cell') {
                
                _cgRemoveCell(row, col);
            } else if (action === 'cg-add-row-above') {
                _cgAddRow(row);
            } else if (action === 'cg-add-row-below') {
                _cgAddRow(row + 1);
            } else if (action === 'cg-remove-row') {
                _cgRemoveRow(row);
            }
        });

        function _cgCommit(rows) {
            saveCellGridRows(rows, true);
            refreshPreview();
            var elementId = $('.impulse-panel-right').data('element-id');
            var s = $('.impulse-panel-right').data('existing-settings') || {};
            s.rows = rows;
            rebuildCellGridEditorPanel(elementId, s, []);
        }
        function _cgRemoveCell(row, col) {
            var rows = getCellGridRows();
            if (!rows[row] || rows[row].widths.length <= 1) return;
            rows[row].widths.splice(col, 1);
            rows[row].cells.splice(col, 1);
            var w = 100 / rows[row].widths.length;
            rows[row].widths = rows[row].widths.map(function() { return Math.round(w * 100) / 100; });
            _cgCommit(rows);
        }
        function _cgAddRow(at) {
            var rows = getCellGridRows();
            if (rows.length >= 6) return;
            var ref = rows[Math.min(at, rows.length - 1)] || { widths: [100] };
            var cellCount = ref.widths ? ref.widths.length : 3;
            var w = 100 / cellCount;
            var widths = [], cells = [];
            for (var i = 0; i < cellCount; i++) { widths.push(Math.round(w * 100) / 100); cells.push({}); }
            rows.splice(at, 0, { widths: widths, cells: cells });
            _cgCommit(rows);
        }
        function _cgRemoveRow(row) {
            var rows = getCellGridRows();
            if (rows.length <= 1) return;
            rows.splice(row, 1);
            _cgCommit(rows);
        }

        $(document).on('click', '.impulse-cg-cell', function(e) {
            if (selectedElementType !== 'rows') return;
            
            var rowIdx = parseInt($(this).data('row'));
            var colIdx = parseInt($(this).data('col'));
            var cellKey = rowIdx + '-' + colIdx;
            var elementId = $('.impulse-panel-right').data('element-id');
            
            var currentSelection = [];
            try { currentSelection = JSON.parse($('input[name="_selected_cells"]').val() || '[]'); } catch(ex) {}
            
            var newSelection;
            if (e.shiftKey) {
                var idx = currentSelection.indexOf(cellKey);
                if (idx > -1) {
                    currentSelection.splice(idx, 1);
                    newSelection = currentSelection;
                } else {
                    newSelection = currentSelection.concat([cellKey]);
                }
            } else {
                if (currentSelection.length === 1 && currentSelection[0] === cellKey) {
                    newSelection = []; 
                } else {
                    newSelection = [cellKey];
                }
            }
            
            var currentSettings = {};
            $('.impulse-panel-right input, .impulse-panel-right select, .impulse-panel-right textarea').each(function() {
                var name = $(this).attr('name');
                if (!name) return;
                currentSettings[name] = $(this).is(':checkbox') ? $(this).is(':checked') : $(this).val();
            });
            currentSettings._selected_cells = newSelection;
            if (typeof currentSettings.rows === 'string') {
                try { currentSettings.rows = JSON.parse(currentSettings.rows); } catch(e) {}
            }
            
            rebuildCellGridEditorPanel(elementId, currentSettings, newSelection);

            try {
                var iframe = document.getElementById('impulse-iframe');
                var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                iframeDoc.querySelectorAll('.impulse-rows-cell').forEach(function(c) { c.classList.remove('selected'); });
                newSelection.forEach(function(key) {
                    var parts = key.split('-');
                    var cell = iframeDoc.querySelector('.impulse-el[data-id="' + elementId + '"] .impulse-rows-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]');
                    if (cell) cell.classList.add('selected');
                });
            } catch(ex) {}
            
            livePreviewSettings(elementId, 'rows');
        });

        
        $(document).on('click', '.impulse-cg-remove-row', function(e) {
            if (selectedElementType !== 'rows') return;
            e.preventDefault(); e.stopPropagation();
            var row = parseInt($(this).data('row'));
            if (isNaN(row)) return;
            _cgRemoveRow(row);
        });

        

        function _rowsDefaultCell(rows) {
            var ref = null;
            (rows || []).forEach(function(r){ (r.cells || []).forEach(function(c){
                if (!ref && c && (c.padding_sides !== undefined || c.padding_top !== undefined || c.padding_bottom !== undefined)) ref = c;
            }); });
            var cell = {};
            if (ref) {
                ['padding_sides','padding_top','padding_bottom'].forEach(function(k){ if (ref[k] !== undefined) cell[k] = ref[k]; });
            } else {
                cell.padding_sides = 10; cell.padding_top = 10; cell.padding_bottom = 10;
            }
            return cell;
        }

        $(document).on('click', '.impulse-cg-add-row', function() {
            if (selectedElementType !== 'rows') return;
            var rows = getCellGridRows();
            if (rows.length >= 6) return;

            var lastRow = rows[rows.length - 1];
            var cellCount = lastRow ? lastRow.widths.length : 3;
            var cellWidth = 100 / cellCount;
            var widths = [];
            var cells = [];
            for (var i = 0; i < cellCount; i++) {
                widths.push(Math.round(cellWidth * 100) / 100);
                cells.push(_rowsDefaultCell(rows));
            }
            rows.push({ widths: widths, cells: cells });
            
            saveCellGridRows(rows, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.rows = rows;
            rebuildCellGridEditorPanel(elementId, settings, []);
        });

        $(document).on('click', '.impulse-cg-row-remove', function(e) {
            e.stopPropagation();
            if (selectedElementType !== 'rows') return;
            var rowIdx = parseInt($(this).data('row'));
            var rows = getCellGridRows();
            if (rows.length <= 1) return;
            
            rows.splice(rowIdx, 1);
            
            saveCellGridRows(rows, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.rows = rows;
            rebuildCellGridEditorPanel(elementId, settings, []);
        });

        

        $(document).on('click', '.impulse-cg-move-row', function(e) {
            e.stopPropagation();
            if (selectedElementType !== 'rows') return;
            var $btn = $(this);
            if ($btn.data('_moving')) return;
            var rowIdx = parseInt($btn.data('row'));
            var dir    = $btn.data('dir');
            var target = dir === 'up' ? rowIdx - 1 : rowIdx + 1;
            var rows   = getCellGridRows();
            if (target < 0 || target >= rows.length) return;
            var elementId = $('.impulse-panel-right').data('element-id');
            if (!elementId) return;
            $btn.data('_moving', true);

            var _tmp = rows[rowIdx]; rows[rowIdx] = rows[target]; rows[target] = _tmp;

            var finish = function() {
                saveCellGridRows(rows, true);
                viewportPreserve.capture();
                refreshPreview();
                var settings = $('.impulse-panel-right').data('existing-settings') || {};
                settings.rows = rows;
                rebuildCellGridEditorPanel(elementId, settings, []);
                $btn.data('_moving', false);
            };

            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(allElements) {
                var arr = (allElements && allElements.elements) || (Array.isArray(allElements) ? allElements : []);
                var kids = arr.filter(function(el) {
                    if (el.parent_id != elementId) return false;
                    var cs = el.settings;
                    if (typeof cs === 'string') { try { cs = JSON.parse(cs); } catch(_e) { cs = {}; } }
                    var cr = (cs && cs._cell_row !== undefined) ? parseInt(cs._cell_row) : 0;
                    return cr === rowIdx || cr === target;
                });
                var pending = kids.length;
                if (!pending) { finish(); return; }
                kids.forEach(function(child) {
                    var cs = child.settings;
                    if (typeof cs === 'string') { try { cs = JSON.parse(cs); } catch(_e) { cs = {}; } }
                    var cr = (cs && cs._cell_row !== undefined) ? parseInt(cs._cell_row) : 0;
                    var newRow = (cr === rowIdx) ? target : rowIdx;
                    $.ajax({
                        url: Impulse.api + 'elements/' + child.id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: { _cell_row: newRow }, page_id: Impulse.pageId })
                    }).always(function() { pending--; if (pending === 0) finish(); });
                });
            }).fail(function() {
                $btn.data('_moving', false);
                window.showToast && window.showToast('Row move failed', 'error');
            });
        });

        $(document).on('click', '.impulse-cg-add-cell', function() {
            if (selectedElementType !== 'rows') return;
            var rowIdx = parseInt($(this).data('row'));
            var rows = getCellGridRows();
            if (!rows[rowIdx]) return;
            if (rows[rowIdx].widths.length >= 6) return;

            var newCount = rows[rowIdx].widths.length + 1;
            var cellWidth = 100 / newCount;
            rows[rowIdx].widths = [];
            for (var i = 0; i < newCount; i++) {
                rows[rowIdx].widths.push(Math.round(cellWidth * 100) / 100);
            }
            if (!rows[rowIdx].cells) rows[rowIdx].cells = [];
            rows[rowIdx].cells.push(_rowsDefaultCell(rows));
            
            saveCellGridRows(rows, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.rows = rows;
            rebuildCellGridEditorPanel(elementId, settings, []);
        });

        $(document).on('click', '.cg-cell-remove', function(e) {
            e.stopPropagation();
            if (selectedElementType !== 'rows') return;
            var rowIdx = parseInt($(this).data('row'));
            var colIdx = parseInt($(this).data('col'));
            var rows = getCellGridRows();
            if (!rows[rowIdx] || rows[rowIdx].widths.length <= 1) return;
            
            rows[rowIdx].widths.splice(colIdx, 1);
            rows[rowIdx].cells.splice(colIdx, 1);

            var cellWidth = 100 / rows[rowIdx].widths.length;
            rows[rowIdx].widths = rows[rowIdx].widths.map(function() { return Math.round(cellWidth * 100) / 100; });
            
            saveCellGridRows(rows, true);
            refreshPreview();
            
            var elementId = $('.impulse-panel-right').data('element-id');
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            settings.rows = rows;
            rebuildCellGridEditorPanel(elementId, settings, []);
        });

        

        

        var _cgPctDrag = null, _cgPctSuppressClick = false;

        $(document).on('click', '.cg-cell-pct', function(e) {
            if (selectedElementType !== 'rows') return;
            e.stopPropagation();
            
            if (_cgPctSuppressClick) { _cgPctSuppressClick = false; return; }
            
            var range = document.createRange();
            range.selectNodeContents(this);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        });

        $(document).on('keydown', '.cg-cell-pct', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.blur();
            }
        });

        

        

        
        if (!window._impulseCgLocks) window._impulseCgLocks = {};
        function _cgLockKey(rowIdx) {
            var id = $('.impulse-panel-right').data('element-id') || 'unknown';
            return id + '#' + rowIdx;
        }
        function _cgGetLock(rowIdx) {
            var k = _cgLockKey(rowIdx);
            if (!window._impulseCgLocks[k]) window._impulseCgLocks[k] = { edited: {} };
            return window._impulseCgLocks[k];
        }
        function _cgClearLock(rowIdx) {
            delete window._impulseCgLocks[_cgLockKey(rowIdx)];
        }

        
        $(document).on('focusout.cgPctLock', '.cg-cell-pct', function() {
            var $row = $(this).closest('.impulse-cg-row');
            var rowIdx = parseInt($row.attr('data-row'));
            setTimeout(function() {

                var $live = $('.impulse-cg-row[data-row="' + rowIdx + '"]');
                if ($live.find('.cg-cell-pct:focus').length === 0) {
                    _cgClearLock(rowIdx);
                }
            }, 0);
        });

        $(document).on('blur', '.cg-cell-pct', function() {

            if (_cgPctDrag && _cgPctDrag.moved) return;
            var $span = $(this);
            var rowIdx = parseInt($span.attr('data-row'));
            var colIdx = parseInt($span.attr('data-col'));
            var newVal = parseInt(($span.text() || '').replace(/[^\d]/g, ''));
            var rows = getCellGridRows();
            if (!rows[rowIdx]) return;
            var widths = rows[rowIdx].widths;
            var n = widths.length;
            
            if (n === 1) { widths[0] = 100; $span.text(100); return; }
            
            if (isNaN(newVal) || newVal < 1) {
                $span.text(Math.round(widths[colIdx] || 0));
                return;
            }

            
            var $row = $span.closest('.impulse-cg-row');
            var st = _cgGetLock(rowIdx);

            
            var candidates = [];
            for (var c = 1; c < n; c++) {
                var idx = (colIdx + c) % n;
                if (idx === colIdx) continue;
                if (!st.edited[idx]) candidates.push(idx);
            }

            
            var lockedOtherSum = 0, lockedOtherCount = 0;
            for (var i = 0; i < n; i++) {
                if (i === colIdx || !st.edited[i]) continue;
                lockedOtherSum += widths[i];
                lockedOtherCount++;
            }
            var unlockedOtherCount = (n - 1) - lockedOtherCount;
            var maxAllowed = 100 - lockedOtherSum - unlockedOtherCount;
            if (maxAllowed < 1) maxAllowed = 1;
            if (newVal > maxAllowed) newVal = maxAllowed;

            
            st.edited[colIdx] = true;

            var delta = widths[colIdx] - newVal; 
            widths[colIdx] = newVal;

            var ci = 0;
            while (delta !== 0 && ci < candidates.length) {
                var ac = candidates[ci];
                if (delta > 0) {
                    widths[ac] += delta;
                    delta = 0;
                } else {
                    var room = widths[ac] - 1;
                    if (room <= 0) { ci++; continue; }
                    var take = Math.min(-delta, room);
                    widths[ac] -= take;
                    delta += take;
                    if (delta < 0) ci++;
                }
            }

            
            if (delta !== 0) {
                widths[colIdx] -= delta;
                if (widths[colIdx] < 1) widths[colIdx] = 1;
            }

            
            var total = 0;
            for (var k = 0; k < n; k++) total += widths[k];
            if (total !== 100) {
                var diff = 100 - total;
                var landed = false;
                for (var m = 0; m < n; m++) {
                    var idx2 = (colIdx + 1 + m) % n;
                    if (idx2 === colIdx) continue;
                    if (st.edited[idx2]) continue;
                    if (widths[idx2] + diff >= 1) { widths[idx2] += diff; landed = true; break; }
                }
                if (!landed) {
                    
                    widths[colIdx] += diff;
                    if (widths[colIdx] < 1) widths[colIdx] = 1;
                }
            }

            for (var p = 0; p < n; p++) {
                $row.find('.impulse-cg-row-cells > .impulse-cg-cell[data-col="' + p + '"]').css('flex', widths[p]);
                $row.find('.cg-cell-pct[data-col="' + p + '"]').text(widths[p]);
            }
            $span.text(widths[colIdx]);
            $('input[name="rows"]').val(JSON.stringify(rows));
            saveCellGridRows(rows, false);
        });

        

        $(document).on('mousedown', '.cg-cell-pct', function(e) {
            if (selectedElementType !== 'rows' || e.which !== 1) return;
            e.stopPropagation(); 
                                 
            var $span = $(this);
            var rowIdx = parseInt($span.attr('data-row'));
            var colIdx = parseInt($span.attr('data-col'));
            var rows = getCellGridRows();
            if (!rows[rowIdx] || (rows[rowIdx].widths || []).length < 2) return; 

            var $cell = $span.closest('.impulse-cg-cell');
            if ($cell.attr('draggable') === 'true') $cell.attr('draggable', 'false');
            _cgPctDrag = {
                rowIdx: rowIdx, colIdx: colIdx,
                startX: e.clientX,
                startVal: parseInt(rows[rowIdx].widths[colIdx]) || 0,
                moved: false, rows: rows,
                $row: $span.closest('.impulse-cg-row'),
                _cell: ($cell.length ? $cell : null)
            };
        });
        $(document).on('mousemove.cgPctDrag', function(e) {
            var d = _cgPctDrag; if (!d) return;
            var dx = e.clientX - d.startX;
            if (!d.moved) {
                if (Math.abs(dx) < 3) return;            
                d.moved = true;
                if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
                document.body.style.cursor = 'ew-resize';
            }
            e.preventDefault();
            var widths = d.rows[d.rowIdx].widths, n = widths.length;
            var nb = (d.colIdx < n - 1) ? d.colIdx + 1 : d.colIdx - 1; 
            var pair = widths[d.colIdx] + widths[nb];
            var newVal = d.startVal + Math.round(dx / 3); 
            newVal = Math.max(1, Math.min(pair - 1, newVal));
            widths[d.colIdx] = newVal;
            widths[nb] = pair - newVal;
            for (var p = 0; p < n; p++) {
                d.$row.find('.impulse-cg-row-cells > .impulse-cg-cell[data-col="' + p + '"]').css('flex', widths[p]);
                d.$row.find('.cg-cell-pct[data-col="' + p + '"]').text(widths[p]);
            }
            $('input[name="rows"]').val(JSON.stringify(d.rows));
        });
        $(document).on('mouseup.cgPctDrag', function() {
            var d = _cgPctDrag; if (!d) return;
            if (d.moved) {
                document.body.style.cursor = '';
                _cgPctSuppressClick = true;              
                saveCellGridRows(d.rows, true);          
            } else if (d._cell) {
                d._cell.attr('draggable', 'true');       
            }
            _cgPctDrag = null;
        });

        

        
        function _cgReorderRow(fromIdx, toIdx) {
            if (fromIdx === toIdx || fromIdx == null || toIdx == null) return;
            var rows = getCellGridRows();
            var n = rows.length;
            if (fromIdx < 0 || fromIdx >= n || toIdx < 0 || toIdx >= n) return;
            var elementId = $('.impulse-panel-right').data('element-id');
            if (!elementId) return;
            
            rows.forEach(function(r, i) { r._oi = i; });
            var moved = rows.splice(fromIdx, 1)[0];
            rows.splice(toIdx, 0, moved);
            var map = {};
            rows.forEach(function(r, ni) { map[r._oi] = ni; delete r._oi; });

            var apply = function() {
                saveCellGridRows(rows, true);
                if (typeof viewportPreserve !== 'undefined' && viewportPreserve && viewportPreserve.capture) viewportPreserve.capture();
                refreshPreview();
                var settings = $('.impulse-panel-right').data('existing-settings') || {};
                settings.rows = rows;
                rebuildCellGridEditorPanel(elementId, settings, []);
            };

            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'GET', headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(allElements) {
                var arr = (allElements && allElements.elements) || (Array.isArray(allElements) ? allElements : []);
                var puts = [];
                arr.forEach(function(el) {
                    if (el.parent_id != elementId) return;
                    var cs = el.settings; if (typeof cs === 'string') { try { cs = JSON.parse(cs); } catch(_e) { cs = {}; } }
                    var cr = (cs && cs._cell_row !== undefined) ? parseInt(cs._cell_row) : 0;
                    var nr = (map[cr] !== undefined) ? map[cr] : cr;
                    if (nr !== cr) puts.push({ id: el.id, row: nr });
                });
                var pending = puts.length;
                if (!pending) { apply(); return; }
                puts.forEach(function(p) {
                    $.ajax({
                        url: Impulse.api + 'elements/' + p.id,
                        method: 'PUT', headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: { _cell_row: p.row }, page_id: Impulse.pageId })
                    }).always(function() { pending--; if (pending === 0) apply(); });
                });
            }).fail(function() { window.showToast && window.showToast('Row reorder failed', 'error'); });
        }

        var _cgRowDrag = null;
        $(document).on('mousedown', '.impulse-cg-row-drag', function(e) {
            if (selectedElementType !== 'rows' || e.which !== 1) return;
            e.preventDefault();
            _cgRowDrag = { fromIdx: parseInt($(this).data('row')), insertIdx: parseInt($(this).data('row')), moved: false, $handle: $(this) };
        });
        $(document).on('mousemove.cgRowDrag', function(e) {
            var d = _cgRowDrag; if (!d) return;
            if (!d.moved) {
                d.moved = true;
                document.body.style.cursor = 'grabbing';
                $('.impulse-cg-row[data-row="' + d.fromIdx + '"]').addClass('cg-row-dragging');
            }
            e.preventDefault();
            $('.cg-row-drop-line').remove(); 
            var $rows = $('.impulse-panel-right .impulse-cg-row');
            
            var insertIdx = $rows.length;
            $rows.each(function(i) {
                var r = this.getBoundingClientRect();
                if (e.clientY < r.top + r.height / 2) { insertIdx = i; return false; }
            });
            d.insertIdx = insertIdx;
            
            var $line = $('<div class="cg-row-drop-line"></div>');
            if (insertIdx >= $rows.length) { $rows.last().after($line); }
            else { $($rows[insertIdx]).before($line); }
        });
        $(document).on('mouseup.cgRowDrag', function() {
            var d = _cgRowDrag; if (!d) return;
            _cgRowDrag = null;
            document.body.style.cursor = '';
            $('.cg-row-dragging').removeClass('cg-row-dragging');
            $('.cg-row-drop-line').remove();
            if (!d.moved) return;
            
            var to = d.insertIdx;
            if (to > d.fromIdx) to -= 1;
            var rows = getCellGridRows();
            to = Math.max(0, Math.min(rows.length - 1, to));
            if (to !== d.fromIdx) _cgReorderRow(d.fromIdx, to);
        });

        
        
        $(document).on('click', '.impulse-rows-merge', function() {
            var selected = getSelectedCellGridCells();
            if (selected.length < 2) return;

            var rowIdx = parseInt(selected[0].split('-')[0]);
            var colIndices = selected.map(function(c) { return parseInt(c.split('-')[1]); }).sort(function(a, b) { return a - b; });

            var isContiguous = true;
            for (var i = 1; i < colIndices.length; i++) {
                if (colIndices[i] !== colIndices[i-1] + 1) {
                    isContiguous = false;
                    break;
                }
            }
            if (!isContiguous) {
                window.showToast && window.showToast('Please select adjacent cells to merge.', 'error');
                return;
            }
            
            var rows = getCellGridRows();
            if (!rows[rowIdx]) return;

            var combinedWidth = 0;
            colIndices.forEach(function(idx) {
                combinedWidth += rows[rowIdx].widths[idx] || 0;
            });

            var firstColIdx = colIndices[0];
            var newWidths = [];
            var newCells = [];
            
            rows[rowIdx].widths.forEach(function(w, idx) {
                if (idx === firstColIdx) {
                    newWidths.push(combinedWidth);
                    newCells.push(rows[rowIdx].cells[idx] || {});
                } else if (colIndices.indexOf(idx) === -1) {
                    newWidths.push(w);
                    newCells.push(rows[rowIdx].cells[idx] || {});
                }
            });
            
            rows[rowIdx].widths = newWidths;
            rows[rowIdx].cells = newCells;
            
            saveCellGridRows(rows, true);  

            var id = $('.impulse-panel-right').data('element-id');
            if (id) {
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: { _selected_cells: [] } }),
                    success: function() {
                        refreshCellGridPanel();
                    }
                });
            }
        });

        $(document).on('input', 'input[name="cell_bg_color"]', function() {
            var val = $(this).val();
            withSelectedCellData(function(cell) { cell.bg_color = val; });
        });

        $(document).on('change', 'input[name="cell_bg_image"]', function() {
            var val = $(this).val();
            var hasImage = val ? true : false;
            withSelectedCellData(function(cell) { cell.bg_image = val; });

            $('.impulse-cell-bg-color-row').toggle(!hasImage);
            $('.impulse-cell-select-image-row').toggle(!hasImage);
            $('.impulse-cell-image-options').toggle(hasImage);
            $('.impulse-cell-hover-options').toggle(hasImage);
        });

        $(document).on('input', 'input[name="cell_overlay"]', function() {
            var val = $(this).val();
            withSelectedCellData(function(cell) { cell.overlay_color = val; });
        });

        

        
        function _applyFrostInline(cellEl, on, bgColor) {
            if (!cellEl) return;
            if (on) {
                cellEl.style.backgroundColor = 'rgba(255,255,255,0.18)';
                cellEl.style.backdropFilter = 'blur(20px) saturate(180%) brightness(1.15)';
                cellEl.style.webkitBackdropFilter = 'blur(20px) saturate(180%) brightness(1.15)';
            } else {
                cellEl.style.backdropFilter = '';
                cellEl.style.webkitBackdropFilter = '';
                cellEl.style.backgroundColor = (bgColor && bgColor !== 'transparent') ? bgColor : '';
            }
        }

        

        

        $(document).on('change', 'input[name="frosted_glass"]', function() {
            var type = selectedElementType;
            if (['grid', 'rows', 'columns'].indexOf(type) === -1) return;
            var on = $(this).is(':checked');
            var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
            var id = $('.impulse-panel-right').data('element-id');
            if (!doc || !id) return;
            var el = doc.querySelector('.impulse-el[data-id="' + id + '"]');
            if (!el) return;
            var sel = type === 'grid' ? '.impulse-grid-cell'
                    : type === 'rows' ? '.impulse-rows-cell'
                    : '.impulse-layout-cell';
            el.querySelectorAll(sel).forEach(function(c) { _applyFrostInline(c, on, ''); });
        });

        $(document).on('click', '.impulse-btn-group[data-name="cell_bg_fit"] button', function() {
            var val = $(this).data('value');
            withSelectedCellData(function(cell) { cell.bg_fit = val; });
        });

        $(document).on('input', 'input[name="cell_hover_overlay"]', function() {
            var val = $(this).val();
            withSelectedCellData(function(cell) { cell.hover_overlay = val; });
        });

        $(document).on('input change', 'input[name="cell_hover_duration"]', function() {
            var val = parseInt($(this).val()) || 300;
            withSelectedCellData(function(cell) { cell.hover_duration = val; });
        });

        $(document).on('input change', 'input[name="cell_padding_top"], input[name="cell_padding_right"], input[name="cell_padding_bottom"], input[name="cell_padding_left"], input[name="cell_padding_sides"]', function() {
            var name = $(this).attr('name');
            var paddingSide = name.replace('cell_padding_', '');
            var val = parseInt($(this).val()) || 0;
            withSelectedCellData(function(cell) { setCellDeviceVal(cell, 'padding_' + paddingSide, val); });
        });

        $(document).on('click', '.impulse-btn-group[data-name="cell_bg_position"] button', function() {
            var val = $(this).data('value');
            withSelectedCellData(function(cell) { cell.bg_position = val; });
        });

        $(document).on('input', 'input[name="cell_url"]', function() {
            var val = $(this).val();
            withSelectedCellData(function(cell) { cell.url = val; });
        });

        $(document).on('click', '.impulse-btn-group[data-name="cell_valign"] button, .impulse-btn-group[data-name="cell_halign"] button', function() {
            var $group = $(this).closest('.impulse-btn-group');
            var name = $group.data('name');
            var val = $group.find('input[type="hidden"]').val();
            var isHalign = name === 'cell_halign';

            withSelectedCellData(function(cell) { 
                setCellDeviceVal(cell, isHalign ? 'halign' : 'valign', val); 
            });

            var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
            if (!doc) return;
            var selected = getSelectedCellGridCells();
            if (selected.length !== 1) return;
            var parts = selected[0].split('-');
            var id = $('.impulse-panel-right').data('element-id');
            var type = selectedElementType;
            var el = doc.querySelector('.impulse-el[data-id="' + id + '"]');
            if (!el) return;
            
            var cellEl;
            if (type === 'rows') {
                cellEl = el.querySelector('.impulse-rows-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]');
            } else if (type === 'columns') {
                cellEl = el.querySelector('.impulse-layout-cell[data-col="' + parts[0] + '"][data-row="' + parts[1] + '"]');
            }
            if (!cellEl) return;
            
            var content = cellEl.querySelector('.impulse-cell-content');
            if (!content) return;
            
            var flexMap = { left: 'flex-start', center: 'center', right: 'flex-end', top: 'flex-start', bottom: 'flex-end', between: 'space-between' };
            if (isHalign) {
                content.style.alignItems = flexMap[val] || 'center';
            } else {
                content.style.justifyContent = flexMap[val] || 'center';
            }
        });

        

        

        function _gridCellSaveAndRefresh(cellIdx, immediateDom) {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            
            autoSaveAndPreview(true);

            
            if (typeof refreshElement === 'function') refreshElement(id);
            if (typeof immediateDom === 'function') {
                try { immediateDom(); } catch (_e) {}
            }
        }

        

        

        
        function _gridCellApplyBorderInline(cellIdx) {
            if (selectedElementType !== 'grid') return;
            var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
            if (!doc) return;
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            var elNode = doc.querySelector('.impulse-el[data-id="' + id + '"]');
            if (!elNode) return;
            var cellEl = elNode.querySelector('.impulse-grid-cell[data-cell="' + cellIdx + '"]');
            if (!cellEl) return;
            var w = parseInt($('input[name="cell_border_width_' + cellIdx + '"]').val(), 10) || 0;
            
            function sideOn(side) {
                var v = $('input[name="cell_border_' + side + '_' + cellIdx + '"]').val();
                return !(v === '0' || v === 0 || v === false || v === '');
            }
            if (w > 0) {
                var bT = sideOn('top')    ? w + 'px' : '0';
                var bR = sideOn('right')  ? w + 'px' : '0';
                var bB = sideOn('bottom') ? w + 'px' : '0';
                var bL = sideOn('left')   ? w + 'px' : '0';
                var color = ($('input[name="cell_border_color_' + cellIdx + '"]').val() || '#e0e0e0').toString();

                
                var gradTo = ($('input[name="cell_border_gradient_to_' + cellIdx + '"]').val() || '').toString();
                var hasGrad = gradTo !== '' && gradTo !== 'transparent' && gradTo.indexOf('rgba(0,0,0,0)') !== 0;
                if (hasGrad) {
                    cellEl.style.borderWidth = '';
                    cellEl.style.borderStyle = '';
                    cellEl.style.borderColor = '';
                    return;
                }
                cellEl.style.borderWidth = bT + ' ' + bR + ' ' + bB + ' ' + bL;
                cellEl.style.borderStyle = 'solid';
                cellEl.style.borderColor = color;

                cellEl.style.boxSizing = 'border-box';
            } else {
                cellEl.style.borderWidth = '';
                cellEl.style.borderStyle = '';
                cellEl.style.borderColor = '';
            }
        }

        $(document).on('click', '.impulse-btn-group[data-name^="cell_halign_"] button, .impulse-btn-group[data-name^="cell_valign_"] button', function() {
            var $group = $(this).closest('.impulse-btn-group');
            var name = $group.data('name');
            var val = $group.find('input[type="hidden"]').val();
            var isHalign = name.indexOf('cell_halign_') === 0;
            var cellIdx = parseInt(name.split('_').pop());
            _gridCellSaveAndRefresh(cellIdx, function() {
                var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
                if (!doc) return;
                var id = $('.impulse-panel-right').data('element-id');
                var el = doc.querySelector('.impulse-el[data-id="' + id + '"]');
                if (!el) return;
                var cellEl = el.querySelector('.impulse-grid-cell[data-cell="' + cellIdx + '"]');
                if (!cellEl) return;
                var flexMap = { left: 'flex-start', center: 'center', right: 'flex-end', top: 'flex-start', bottom: 'flex-end', between: 'space-between' };
                if (isHalign) cellEl.style.alignItems = flexMap[val] || 'center';
                else cellEl.style.justifyContent = flexMap[val] || 'center';
            });
        });

        

        
        
        $(document).on('input change',
            'input[name^="cell_pad_h_"], input[name^="cell_pad_v_"], input[name^="cell_gap_"], ' +
            'input[name^="cell_rotate_"], input[name^="cell_scale_"]', function() {
            if (selectedElementType !== 'grid') return;
            var nm = $(this).attr('name') || '';
            var cellIdx = parseInt(nm.split('_').pop());
            var v = parseInt($(this).val()) || 0;
            _gridCellSaveAndRefresh(cellIdx, function() {
                var doc = window.impulseCSSVars ? window.impulseCSSVars.getDoc() : null;
                if (!doc) return;
                var id = $('.impulse-panel-right').data('element-id');
                var el = doc.querySelector('.impulse-el[data-id="' + id + '"]');
                if (!el) return;
                var cellEl = el.querySelector('.impulse-grid-cell[data-cell="' + cellIdx + '"]');
                if (!cellEl) return;
                if (nm.indexOf('cell_pad_h_') === 0) {
                    cellEl.style.paddingLeft = v + 'px';
                    cellEl.style.paddingRight = v + 'px';
                } else if (nm.indexOf('cell_pad_v_') === 0) {
                    cellEl.style.paddingTop = v + 'px';
                    cellEl.style.paddingBottom = v + 'px';
                } else if (nm.indexOf('cell_gap_') === 0) {
                    cellEl.style.gap = v + 'px';
                } else if (nm.indexOf('cell_rotate_') === 0 || nm.indexOf('cell_scale_') === 0) {

                    
                    
                    var rot = parseInt($('input[name="cell_rotate_' + cellIdx + '"]').val()) || 0;
                    var scl = parseInt($('input[name="cell_scale_' + cellIdx + '"]').val()) || 100;
                    var parts = [];
                    if (rot !== 0) parts.push('rotate(' + rot + 'deg)');
                    if (scl !== 100) parts.push('scale(' + (scl / 100) + ')');
                    cellEl.style.transformOrigin = 'center';
                    cellEl.style.transform = parts.length ? parts.join(' ') : '';

                    

                    if (rot !== 0) cellEl.setAttribute('data-cell-rotate', rot);
                    else cellEl.removeAttribute('data-cell-rotate');
                    if (scl !== 100) cellEl.setAttribute('data-cell-scale', scl);
                    else cellEl.removeAttribute('data-cell-scale');
                }
            });
        });

        $(document).on('input change', 'input[name="cell_border_width"]', function() {
            var val = parseInt($(this).val()) || 0;
            
            $(this).closest('.impulse-margin-grid').siblings('.impulse-border-sides').css('display', val > 0 ? 'flex' : 'none');
            withSelectedCellData(function(cell) { cell.border_width = val; });
        });

        

        

        

        

        

        
        $(document).on('click', '.impulse-cell-border-width-btn', function() {
            var $btn = $(this);

            
            var w   = parseInt($btn.attr('data-width'), 10);
            if (isNaN(w)) w = 0;
            var idx = $btn.attr('data-cell-idx');
            var $wrapper = $btn.closest('.impulse-cell-border-cell');
            var $input   = $wrapper.find('input[name="cell_border_width_' + idx + '"]');
            var cur = parseInt($input.val(), 10);
            if (isNaN(cur)) cur = 0;
            
            var nextVal = (cur === w) ? 0 : w;
            $input.val(String(nextVal));
            $wrapper.find('.impulse-cell-border-width-btn').removeClass('active');
            if (nextVal > 0) {
                $wrapper.find('.impulse-cell-border-width-btn[data-width="' + nextVal + '"]').addClass('active');
            }

            $wrapper.find('.impulse-border-side-btn').each(function() {
                var $eBtn = $(this);
                var stored = $eBtn.attr('data-stored') === '1';
                $eBtn.toggleClass('active', nextVal > 0 && stored);
            });
            $input.trigger('change');

            
            _gridCellApplyBorderInline(parseInt(idx, 10));
            autoSaveAndPreview(true);
        });

        

        

        
        $(document).on('input change', 'input.impulse-color-text[name^="cell_border_color_"]', function() {
            if (selectedElementType !== 'grid') return;
            var nm = $(this).attr('name') || '';

            
            var m = nm.match(/^cell_border_color_(\d+)$/);
            if (!m) return;
            _gridCellApplyBorderInline(parseInt(m[1], 10));
            autoSaveAndPreview(true);
        });

        $(document).on('input', '.impulse-cell-settings-section input[name="cell_border_color"]', function() {
            var val = $(this).val();
            withSelectedCellData(function(cell) { cell.border_color = val; });
        });

        $(document).on('click', '.impulse-cell-settings-section .impulse-border-side-btn', function(e) {
            e.stopPropagation(); 
            
            var $btn = $(this);
            var side = $btn.data('side');
            var $input = $btn.next('input[type="hidden"]');
            var isActive = $btn.hasClass('active');
            
            if (isActive) {
                $btn.removeClass('active');
                $input.val('0');
            } else {
                $btn.addClass('active');
                $input.val('1');
            }
            
            var newVal = isActive ? '0' : '1';
            withSelectedCellData(function(cell) { cell['border_' + side] = newVal; }, true);
        });

        $(document).on('change', 'input[name="bg_image"]', function() {
            var hasImage = $(this).val() ? true : false;
            $('[data-show-if-container-image]').toggle(hasImage);
        });

        $(document).on('click', '.impulse-btn-group[data-name="source"] button', function() {
            var source = $(this).data('value');
            if (source === 'self') {
                $('.impulse-video-external').hide();
                $('.impulse-video-self').show();
            } else {
                $('.impulse-video-external').show();
                $('.impulse-video-self').hide();
            }
        });

        

        
        $(document).on('click', '#impulse-select-video-file', function() {
            if (typeof openImglibPicker !== 'function') return;
            openImglibPicker({ label: 'Select Video', noFocal: true }, function(attachment) {
                if (!attachment || !attachment.url) return;
                var url = attachment.url;
                $('input[name="video_url"]').val(url);
                if ($('input[name="video_file_url"]').length) {
                    $('input[name="video_file_url"]').val(url);
                } else {
                    $('<input type="hidden" name="video_file_url">').val(url).appendTo('#impulse-settings-body');
                }
                
                var fname = url.split('/').pop();
                $('.impulse-video-file-row span').text(fname);
                $('.impulse-video-url-row').hide();
                $('.impulse-video-file-row').show();
                $('.impulse-video-thumb-preview').hide();
                if (typeof autoSaveAndRefresh === 'function') autoSaveAndRefresh();
            });
        });

        $(document).on('click', '.impulse-select-section-bg-video', function() {
            if (typeof wp !== 'undefined' && wp.media) {
                var frame = wp.media({ title: 'Select Background Video', multiple: false, library: { type: 'video' } });
                frame.on('select', function() {
                    var video = frame.state().get('selection').first().toJSON();
                    $('input[name="bg_video"]').val(video.url);
                    $('.impulse-bg-video-fallback-row').css('display');
                    $('.impulse-overlay-section').show();
                    autoSaveAndRefresh();
                });
                frame.open();
            }
        });

        $(document).on('blur', 'input[name="bg_video"]', function() {
            var url = $(this).val().trim();
            if (url) {
                $('.impulse-bg-video-fallback-row').css('display');
                $('.impulse-overlay-section').show();
            } else {
                $('.impulse-bg-video-fallback-row').hide();
                if (!$('input[name="bg_image"]').val()) { $('.impulse-overlay-section').hide(); }
            }
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-select-section-bg-fallback', function() {
            if (typeof wp !== 'undefined' && wp.media) {
                var frame = wp.media({ title: 'Select Fallback Image', multiple: false, library: { type: 'image' } });
                frame.on('select', function() {
                    var img = frame.state().get('selection').first().toJSON();
                    $('input[name="bg_video_fallback"]').val(img.url);
                    autoSaveAndRefresh();
                });
                frame.open();
            }
        });

        $(document).on('click', '.impulse-remove-section-bg-fallback', function() {
            $('input[name="bg_video_fallback"]').val('');
            autoSaveAndRefresh();
        });

        $(document).on('input change', 'input[name="video_url"]', function() {
            var url = $(this).val();
            var $preview = $('.impulse-video-thumb-preview');
            if (!$preview.length) return;
            var ytMatch = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
            if (ytMatch) {
                $preview.find('img').attr('src', 'https://img.youtube.com/vi/' + ytMatch[1] + '/hqdefault.jpg');
                $preview.show();
            } else {
                $preview.hide();
            }
        });
        
        $(document).on('blur', 'input[name="video_url"]', function() {
            if (selectedElementType === 'video') autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-btn-group[data-name="view"] button', function() {
            var view = $(this).data('value');
            if (view === 'default' || view === 'square') {
                $('.impulse-icon-view-settings').hide();
                $('.impulse-icon-shape-settings').hide();
            } else {
                $('.impulse-icon-view-settings').show();
                $('.impulse-icon-shape-settings').show();
                
                var bgLabel = view === 'framed' ? 'Border' : 'Fill';
                $('.impulse-icon-bg-column .impulse-setting-label').text(bgLabel);
            }
        });

        
        
        $(document).on('change', 'input[name="text_shadow"]', function() {
            if ($(this).is(':checked')) {
                $('.impulse-text-shadow-settings').show();
            } else {
                $('.impulse-text-shadow-settings').hide();
            }
            autoSaveAndPreview();
        });

        $(document).on('change', 'input[name="fit_text"]', function() {
            var isEnabled = $(this).is(':checked');
            $('.impulse-fit-text-hint').toggle(isEnabled);
            $('.impulse-size-settings').toggle(!isEnabled);
            $('.impulse-fit-text-settings').toggle(isEnabled);
            autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-setting-section-header', function(e) {
            
            if ($(e.target).closest('.impulse-toggle-sm').length) return;
            
            var $section = $(this).closest('.impulse-setting-section');
            var isCollapsed = $section.hasClass('collapsed');

            $section.siblings('.impulse-setting-section').addClass('collapsed');

            if (isCollapsed) {
                $section.removeClass('collapsed');
            } else {
                $section.addClass('collapsed');
            }
        });

        $(document).on('click', '.impulse-btn-group[data-name="text_position"] button', function() {
            var pos = $(this).data('value');
            if (pos === 'left' || pos === 'right') {
                $('.impulse-icon-valign-settings').show();
                $('.impulse-icon-align-settings').hide();
            } else {
                $('.impulse-icon-valign-settings').hide();
                $('.impulse-icon-align-settings').show();
            }
        });

        $(document).on('click', '.impulse-btn-group[data-name="columns"] button', function() {
            var cols = $(this).data('value');
            if (cols && cols !== '1') {
                $('.impulse-column-gap-slider').css({'opacity': '1', 'pointer-events': 'auto'});
            } else {
                $('.impulse-column-gap-slider').css({'opacity': '0.4', 'pointer-events': 'none'});
            }
        });

        $(document).on('click', '.impulse-btn-group[data-name="on_submit"] button', function() {
            var action = $(this).data('value');
            $(this).closest('.impulse-btn-group').find('input[type="hidden"]').val(action);
            
            if (action === 'redirect') {
                $('.impulse-form-message-settings').hide();
                $('.impulse-form-redirect-settings').show();
            } else {
                $('.impulse-form-message-settings').show();
                $('.impulse-form-redirect-settings').hide();
            }
        });

        $(document).on('input change', 'input[name="field_hover_bg"]', function() {
            var hoverColor = $(this).val();
            var normalColor = $('input[name="field_bg"]').val() || '#ffffff';
            var $hoverSpeedRow = $('.impulse-hover-speed-row');
            
            if (hoverColor && hoverColor !== '' && hoverColor !== normalColor) {
                $hoverSpeedRow.show();
            } else {
                $hoverSpeedRow.hide();
            }
        });

        $(document).on('click', '#impulse-select-button-icon', function() {
            loadIcons();
            $('#impulse-icon-modal').data('target', 'icon').show();
        });

        $(document).on('change', 'input[name="icon"]', function() {
            $('.impulse-btn-simple-settings').toggle(!!$(this).val());
        });

        $(document).on('click', '.impulse-btn-group[data-name="entrance_animation"] button', function(e) {
            
            var val = $(this).closest('.impulse-btn-group').find('input[type="hidden"]').val();
            var show = val !== 'none';
            $('.impulse-entrance-controls').toggle(show);
            $('.impulse-entrance-direction').toggle(val === 'unveil');
            $('.impulse-entrance-intensity').toggle(show && val !== 'unveil');
            if (show) previewAnimation(val);
        });

        

        
        
        function previewTextReveal() {
            var id  = $('.impulse-panel-right').data('element-id');
            var ifr = document.getElementById('impulse-iframe');
            if (!id || !ifr) return;
            var doc = ifr.contentDocument || ifr.contentWindow.document;
            if (!doc) return;
            var node = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-text');
            if (!node) return;
            
            var inner = node.querySelector('[contenteditable]') || node;
            var mode = ($('input[name="text_reveal"]').val() || 'none');
            if (mode === 'none') return;
            
            var stagger  = parseFloat($('input[name="text_reveal_stagger"]').val());
            var duration = parseFloat($('input[name="text_reveal_duration"]').val());
            if (isNaN(stagger))  stagger  = (mode === 'chars' ? 0.02 : (mode === 'lines' ? 0.12 : 0.04));
            if (isNaN(duration)) duration = 0.8;

            

            if (!doc.documentElement.dataset.ttrCss) {

                

                

                
                var css = '.impulse-text-reveal{--ttr-stagger:0.04s;--ttr-duration:0.8s;--ttr-delay:0s}'
                        + '.impulse-text-reveal [contenteditable]{background-image:inherit;background-clip:inherit;-webkit-background-clip:inherit;-webkit-text-fill-color:inherit;color:inherit}'
                        + '.impulse-text-reveal .impulse-tr-word,'
                        + '.impulse-text-reveal .impulse-tr-line,'
                        + '.impulse-text-reveal .impulse-tr-char{display:inline-block;opacity:0;background-image:inherit;background-clip:inherit;-webkit-background-clip:inherit;-webkit-text-fill-color:inherit;color:inherit}'
                        + '.impulse-text-reveal-lines .impulse-tr-line{display:block}'
                        + '.impulse-text-reveal.is-revealed .impulse-tr-word,'
                        + '.impulse-text-reveal.is-revealed .impulse-tr-line,'
                        + '.impulse-text-reveal.is-revealed .impulse-tr-char{'
                        +   'animation:impulse-tr-fadeup var(--ttr-duration) cubic-bezier(0.4, 0, 0.2, 1) both;'
                        +   'animation-delay:calc(var(--ttr-delay) + var(--i,0) * var(--ttr-stagger))}'
                        + '@keyframes impulse-tr-fadeup{from{opacity:0;transform:translateY(0.5em)}to{opacity:1;transform:translateY(0)}}'
                        + '.impulse-text-reveal-chars.is-revealed .impulse-tr-char{animation-name:impulse-tr-pop}'
                        + '@keyframes impulse-tr-pop{from{opacity:0;transform:scale(0.5)}to{opacity:1;transform:scale(1)}}'
                        + '.impulse-text-reveal-sweep{'
                        +   '-webkit-mask-image:linear-gradient(90deg,transparent 0%,transparent 40%,#000 60%,#000 100%);'
                        +   'mask-image:linear-gradient(90deg,transparent 0%,transparent 40%,#000 60%,#000 100%);'
                        +   '-webkit-mask-size:250% 100%;mask-size:250% 100%;'
                        +   '-webkit-mask-position:0% 0;mask-position:0% 0;'
                        +   '-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}'
                        + '.impulse-text-reveal-sweep.is-revealed{animation:impulse-tr-sweep var(--ttr-duration) cubic-bezier(0.4, 0, 0.2, 1) both}'
                        + '@keyframes impulse-tr-sweep{from{-webkit-mask-position:0% 0;mask-position:0% 0}to{-webkit-mask-position:100% 0;mask-position:100% 0}}';
                var s = doc.createElement('style');
                s.textContent = css;
                doc.head.appendChild(s);
                doc.documentElement.dataset.ttrCss = '1';
            }

            
            ['impulse-text-reveal-words','impulse-text-reveal-lines','impulse-text-reveal-chars','impulse-text-reveal-sweep']
                .forEach(function(c) { node.classList.remove(c); });
            node.classList.remove('is-revealed');
            node.classList.add('impulse-text-reveal', 'impulse-text-reveal-' + mode);
            node.style.setProperty('--ttr-stagger',  stagger  + 's');
            node.style.setProperty('--ttr-duration', duration + 's');

            if (mode === 'sweep') {
                void node.offsetWidth;
                node.classList.add('is-revealed');
                return;
            }

            
            var origHtml = inner.dataset.ttrOrig;
            if (!origHtml) {
                origHtml = inner.innerHTML;
                inner.dataset.ttrOrig = origHtml;
            }
            
            inner.innerHTML = origHtml;

            var wrapped = wrapForReveal(origHtml, mode);
            inner.innerHTML = wrapped;

            
            void node.offsetWidth;
            node.classList.add('is-revealed');

            var spans = inner.querySelectorAll('.impulse-tr-word,.impulse-tr-line,.impulse-tr-char');
            var lastDelay = (spans.length - 1) * stagger; 
            
            setTimeout(function() {
                inner.innerHTML = origHtml;
                delete inner.dataset.ttrOrig;
                node.classList.remove('is-revealed');
            }, (duration + lastDelay) * 1000 + 200);
        }

        
        
        function wrapForReveal(html, mode) {
            if (mode === 'sweep' || !html) return html;
            if (mode === 'lines') {
                var parts = html.split(/<br\s*\/?>|\r?\n/i);
                var li = 0, out = '';
                parts.forEach(function(p) {
                    var t = p.replace(/^\s+|\s+$/g, '');
                    if (!t) return;
                    out += '<span class="impulse-tr-line" style="--i:' + (li++) + '">' + t + '</span>';
                });
                return out;
            }
            
            var chunks = html.split(/(<[^>]+>)/);
            var idx = 0, result = '';
            chunks.forEach(function(c) {
                if (!c) return;
                if (c.charAt(0) === '<') { result += c; return; }
                if (mode === 'words') {
                    result += c.replace(/(\S+)/g, function(m) {
                        return '<span class="impulse-tr-word" style="--i:' + (idx++) + '">' + m + '</span>';
                    });
                } else if (mode === 'chars') {
                    for (var i = 0; i < c.length; i++) {
                        var ch = c.charAt(i);
                        if (/\s/.test(ch)) { result += ch; continue; }
                        result += '<span class="impulse-tr-char" style="--i:' + (idx++) + '">' + ch + '</span>';
                    }
                } else {
                    result += c;
                }
            });
            return result;
        }

        

        
        $(document).on('change', 'input[name="text_reveal_stagger"], input[name="text_reveal_duration"], input[name="text_reveal_delay"]', function() {
            previewTextReveal();
        });
        
        $(document).on('click', '.impulse-text-reveal-preview-btn', function() {
            previewTextReveal();
        });
        
        $(document).on('click', '.impulse-btn-group[data-name="unveil_direction"] button', function() {
            var val = $(this).data('value');
            $('input[name="unveil_direction"]').val(val).trigger('change');
            previewAnimation('unveil');
        });

        $(document).on('click', '.impulse-btn-group[data-name="alert_style"] button', function() {
            var val = $(this).data('value');
            var presets = {
                'info':    { bg: ''+ImpC.panel+'', text: ''+ImpC.text+'' },
                'success': { bg: ''+ImpC.panel+'', text: ''+ImpC.text+'' },
                'warning': { bg: ''+ImpC.panel+'', text: ''+ImpC.muted+'' },
                'error':   { bg: ''+ImpC.surface+'', text: ''+ImpC.dim+'' }
            };
            if (presets[val]) {
                var p = presets[val];
                
                var $body = $(this).closest('#impulse-settings-body');
                $body.find('input[name="bg_color"]').val(p.bg).trigger('change');
                $body.find('input[name="text_color"]').val(p.text).trigger('change');
                
                $body.find('input[name="bg_color"]').closest('.impulse-color-picker-wrap, div').find('.impulse-color-swatch').css('--swatch-color', p.bg);
                $body.find('input[name="text_color"]').closest('.impulse-color-picker-wrap, div').find('.impulse-color-swatch').css('--swatch-color', p.text);
                
                $body.find('input[name="show_icon"]').val('1');
                $body.find('.impulse-btn-group[data-name="show_icon"] button').removeClass('active');
                $body.find('.impulse-btn-group[data-name="show_icon"] button[data-value="1"]').addClass('active');
            }
        });

        $(document).on('change', 'input[name="fade_edges"]', function() {
            var id = $('.impulse-panel-right').data('element-id');
            var ifr = document.getElementById('impulse-iframe');
            if (!id || !ifr) return;
            var doc = ifr.contentDocument || ifr.contentWindow.document;
            if (!doc) return;
            var inner = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-divider-inner');
            if (!inner) return;
            var on = $(this).is(':checked');
            var mask = on ? 'linear-gradient(90deg,transparent 0%,#000 12%,#000 88%,transparent 100%)' : 'none';
            inner.style.maskImage = mask;
            inner.style.webkitMaskImage = mask;
        });

        $(document).on('input', 'input[name="label"]', function() {
            var id = $('.impulse-panel-right').data('element-id');
            var ifr = document.getElementById('impulse-iframe');
            if (!id || !ifr) return;
            if (selectedElementType !== 'divider') return;
            var doc = ifr.contentDocument || ifr.contentWindow.document;
            if (!doc) return;
            var outer = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-divider');
            if (!outer) return;
            var val = $(this).val() || '';
            var existing = outer.querySelector(':scope > .impulse-divider-label');
            if (!val.trim()) {
                if (existing) existing.remove();
                return;
            }
            if (!existing) {
                existing = doc.createElement('span');
                existing.className = 'impulse-divider-label';
                existing.style.cssText = 'position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:11px;font-weight:600;letter-spacing:2px;text-transform:uppercase;padding:4px 14px;border-radius:2px;background:var(--impulse-divider-label-bg,rgba(0,0,0,0.75));color:var(--impulse-divider-label-fg,#fff);pointer-events:none;white-space:nowrap;z-index:4;';
                outer.appendChild(existing);
            }
            existing.textContent = val;
        });

        $(document).on('change', 'select[name="hover_effect"]', function() {
            var val = $(this).val();
            if (val && val !== 'none') {
                $('.impulse-hover-effect-settings').show();
                $('.impulse-hover-effect-speed').show();
                $('.impulse-hover-effect-speed-placeholder').hide();
            } else {
                $('.impulse-hover-effect-settings').hide();
                $('.impulse-hover-effect-speed').hide();
                $('.impulse-hover-effect-speed-placeholder').show();
            }
            autoSaveAndPreview();
        });

        $(document).on('click', '.impulse-animation-preview-btn', function(e) {
            e.preventDefault();
            var animation = $('input[name="entrance_animation"]').val();
            if (animation && animation !== 'none') {
                previewAnimation(animation);
            }
        });

        function previewAnimation(animation) {
            if (!selectedElementId) return;
            
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentDocument) return;
            
            var el = iframe.contentDocument.querySelector('.impulse-el[data-id="' + selectedElementId + '"]');
            if (!el) return;

            el.style.animation = '';
            el.style.opacity = '';
            el.style.transform = '';
            el.style.filter = '';
            el.style.clipPath = '';

            void el.offsetWidth;

            var duration = parseFloat($('input[name="animation_duration"]').val()) || 0.6;
            var intensity = parseInt($('input[name="entrance_intensity"]').val()) || 50;
            var t = intensity / 100;

            if (animation === 'emerge') {
                el.style.setProperty('--ea-scale', (1 - t * 0.2).toFixed(3));
                el.style.setProperty('--ea-blur', (t * 8).toFixed(1) + 'px');
            } else if (animation === 'surface') {
                el.style.setProperty('--ea-depth', (-t * 120).toFixed(0) + 'px');
                el.style.setProperty('--ea-tilt', (t * 30).toFixed(0) + 'deg');
            } else if (animation === 'resolve') {
                el.style.setProperty('--ea-blur', (t * 20).toFixed(1) + 'px');
            }
            
            var animName = 'impulse-' + animation;
            if (animation === 'unveil') {
                var dir = $('input[name="unveil_direction"]').val() || 'up';
                animName = 'impulse-unveil-' + dir;
            }
            
            el.style.animation = animName + ' ' + duration + 's cubic-bezier(0.4, 0, 0.2, 1) forwards';

            setTimeout(function() {
                el.style.animation = '';
                el.style.removeProperty('--ea-scale');
                el.style.removeProperty('--ea-blur');
                el.style.removeProperty('--ea-depth');
                el.style.removeProperty('--ea-tilt');
            }, duration * 1000 + 100);
        }

        window.impulseFlipEditingSide = 'front';
        function applyFlipBoxEditState() {
            if (selectedElementType !== 'flip_box') return;
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentDocument) return;
            var el = iframe.contentDocument.querySelector('.impulse-el[data-id="' + selectedElementId + '"] .impulse-flip-box');
            if (!el) return;
            var inner = el.querySelector('.impulse-flip-inner');
            if (!inner) return;
            var anim = el.dataset.animation || 'flip';
            var side = window.impulseFlipEditingSide;
            var front = el.querySelector('.impulse-flip-front');
            var back = el.querySelector('.impulse-flip-back');
            
            inner.style.transition = 'none';
            if (front) front.style.transition = 'none';
            if (back) back.style.transition = 'none';
            if (side === 'back') {

                

                

                if (anim === 'spring') {
                    var dir = el.dataset.flipDirection || 'horizontal';
                    inner.style.transform = dir === 'vertical' ? 'rotateX(180deg)' : 'rotateY(180deg)';
                } else if (anim === 'cube') {
                    inner.style.transform = 'rotateX(90deg)';
                } else if (anim === 'push') {
                    var sd = el.dataset.slideDirection || 'left';
                    var pushMap = { left: 'translateX(-100%)', right: 'translateX(100%)', up: 'translateY(-100%)', down: 'translateY(100%)' };
                    inner.style.transform = pushMap[sd] || pushMap.left;
                } else {

                    
                    
                    if (front) { front.style.opacity = '0'; front.style.zIndex = '1'; }
                    if (back) { back.style.opacity = '1'; back.style.zIndex = '2'; back.style.transform = 'none'; }
                }
                
                el.style.pointerEvents = 'none';
                inner.style.pointerEvents = 'none';
            } else {
                
                inner.style.transform = '';
                if (front) {
                    front.style.opacity = '';
                    front.style.zIndex = '2';
                    front.style.clipPath = '';
                }
                if (back) {
                    back.style.opacity = '';
                    back.style.zIndex = '1';
                    back.style.transform = '';
                }
                el.style.pointerEvents = '';
                inner.style.pointerEvents = '';
            }
            
            requestAnimationFrame(function() {
                if (inner) inner.style.transition = '';
                if (front) front.style.transition = '';
                if (back) back.style.transition = '';
            });
        }

        $(document).on('click', '.impulse-settings-subtab', function() {
            var tab = $(this).data('tab');
            var $wrapper = $(this).closest('.impulse-style-subtabs-wrap');

            $(this).siblings().removeClass('active');
            $(this).addClass('active');

            var $container = $wrapper.length ? $wrapper : $(this).closest('.impulse-panel-content, .impulse-settings-section, .impulse-panel-right');
            $container.find('.impulse-subtab-content').removeClass('active');
            $container.find('.impulse-subtab-content[data-tab="' + tab + '"]').addClass('active');

            if (selectedElementType === 'flip_box' && (tab === 'front' || tab === 'back')) {
                window.impulseFlipEditingSide = tab;
                applyFlipBoxEditState();
            }

            if (selectedElementType === 'products' || selectedElementType === 'products') {
                
                $container.find('input[name="_panel_subtab"]').val(tab);
                if (tab === 'modal') {
                    
                    postToIframe({ type: 'impulse-quickview-preview-open' });
                    setTimeout(function() {
                        postToIframe({ type: 'impulse-quickview-preview-open' });
                        postModalStylesToIframe();
                    }, 300);
                } else {
                    postToIframe({ type: 'impulse-quickview-preview-close' });
                }
            }
        });

        function postModalStylesToIframe() {
            if (selectedElementType !== 'products' && selectedElementType !== 'products') return;
            var s = {};
            var numFields = ['max_width','height','border_radius','overlay_opacity','details_padding','desc_size'];
            var strFields = ['show_desc_type'];
            var boolFields = ['show_desc','show_price','show_qty'];
            numFields.forEach(function(f) {
                s[f] = parseInt($('input[name="modal_design_' + f + '"]').val()) || 0;
            });
            strFields.forEach(function(f) {
                s[f] = $('input[name="modal_design_' + f + '"]').val() || '';
            });
            boolFields.forEach(function(f) {
                s[f] = $('input[name="modal_design_' + f + '"]').is(':checked');
            });
            
            s.card_shadow = $('input[name="card_design_card_shadow"]').val() || '';
            s.card_bg     = $('input[name="card_design_card_background"]').val() || '#ffffff';
            postToIframe({ type: 'impulse-update-quickview-styles', settings: s });
        }

        $(document).on('click', '#impulse-select-icon', function() {
            loadIcons();
            $('#impulse-icon-modal').data('target', 'icon').show();
        });

        
        
        $(document).on('click', '#impulse-upload-icon-image', function() {
            openImglibPicker({ label: 'Select Icon Image' }, function(attachment) {
                if (attachment.url) {
                    $('input[name="icon_image"]').val(attachment.url);
                    autoSaveAndRefresh();
                }
            });
        });

        $(document).on('click', '.impulse-remove-icon-image', function() {
            $('input[name="icon_image"]').val('');
            $(this).closest('.impulse-icon-image-preview').remove();
            autoSaveAndRefresh();
        });
        
        function loadIcons() {
            
            if (!loadIcons._html) {
                var html = '<div class="impulse-icon-item" data-icon="none" title="No icon" style="opacity:0.5"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg></div>';
                var names = Object.keys(window.ImpulseLucideAll || LucidePickerSVG || {}).sort();
                names.forEach(function(name) {
                    html += '<div class="impulse-icon-item" data-icon="' + name + '" title="' + name.replace(/-/g, ' ') + '">' + lucideSvg(name, 18) + '</div>';
                });
                loadIcons._html = html;
            }
            $('#impulse-icon-grid').html(loadIcons._html);
            var $s = $('#impulse-icon-search');
            if ($s.length) { $s.val(''); $s.trigger('input'); setTimeout(function() { $s.focus(); }, 30); }
        }
        
        $(document).on('input', '#impulse-icon-search', function() {
            var q = ($(this).val() || '').toLowerCase().trim();
            $('#impulse-icon-grid .impulse-icon-item').each(function() {
                var n = $(this).attr('data-icon') || '';
                this.style.display = (!q || n.indexOf(q) !== -1) ? '' : 'none';
            });
        });

        $(document).on('click', '.impulse-icon-item', function() {
            var icon = $(this).data('icon');
            var target = $('#impulse-icon-modal').data('target') || 'icon';

            if (target === 'icon_list_item') {
                var $btn = $('#impulse-icon-modal').data('icon-list-btn');
                if ($btn && $btn.length) {
                    
                    $btn.html(lucideSvg(icon, 12) + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span>');

                    $btn.closest('.impulse-table-item-edit').data('icon', icon);

                    var storedItems = [];
                    try { storedItems = JSON.parse($('input[name="items"]').val() || '[]'); } catch(e) {}
                    var items = [];
                    $('.impulse-table-item-edit').each(function(i) {
                        var isUrlMode = $(this).hasClass('impulse-url-mode');
                        var inputVal = $(this).find('.impulse-table-text').val();
                        items.push({
                            icon: $(this).data('icon') || 'circle',
                            text: isUrlMode ? (storedItems[i] ? storedItems[i].text : '') : inputVal,
                            url: isUrlMode ? inputVal : ($(this).data('url') || (storedItems[i] ? storedItems[i].url : '') || '')
                        });
                    });
                    $('input[name="items"]').val(JSON.stringify(items)).trigger('change');
                }
                $('#impulse-icon-modal').removeData('target').removeData('icon-list-btn').hide();
                autoSaveAndRefresh();
                return;
            }

            if (target === 'net_card') {
                var $nb = $('#impulse-icon-modal').data('net-card-btn');
                if ($nb && $nb.length) {
                    $nb.attr('data-icon', icon).html(lucideSvg(icon, 16));
                    if (typeof updateNetCardsJSON === 'function') updateNetCardsJSON();
                }
                $('#impulse-icon-modal').removeData('target').removeData('net-card-btn').hide();
                autoSaveAndRefresh();
                return;
            }

            if (target === 'mq_card') {
                var $mb = $('#impulse-icon-modal').data('mq-card-btn');
                if ($mb && $mb.length) {
                    $mb.attr('data-icon', icon).html(lucideSvg(icon, 16));
                    if (typeof updateMarqueeCardsJSON === 'function') updateMarqueeCardsJSON();
                }
                $('#impulse-icon-modal').removeData('target').removeData('mq-card-btn').hide();
                autoSaveAndRefresh();
                return;
            }

            if (target === 'price_list_item') {
                var $btn = $('#impulse-icon-modal').data('pl-icon-btn');
                if ($btn && $btn.length) {
                    if (icon === 'none') {
                        $btn.html('<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="#666" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg><span class="impulse-icon-copy-down" title="Copy icon to next row"></span>');
                    } else {
                        $btn.html(lucideSvg(icon, 12) + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span>');
                    }
                    $btn.closest('.impulse-pl-item').data('icon', icon).attr('data-icon', icon);
                    collectPriceListItems();
                }
                $('#impulse-icon-modal').removeData('target').removeData('pl-icon-btn').hide();
                autoSaveAndRefresh();
                return;
            }

            if (target === 'badge' && currentBadgeItem) {
                currentBadgeItem.find('.impulse-badge-icon').val(icon);
                currentBadgeItem.find('.impulse-badge-svg').val(''); 

                var color = currentBadgeItem.find('.impulse-badge-color-picker').val() || currentBadgeItem.find('.impulse-badge-color-hex').val() || '#666666';
                currentBadgeItem.find('.impulse-badge-preview').html(lucideSvg(icon, 16)).css('color', color);
                
                $('#impulse-icon-modal').removeData('target').hide();
                currentBadgeItem = null;
                saveBadgesAndPreview();
                return;
            }
            
            $('input[name="' + target + '"]').val(icon).trigger('change');
            
            $('input[name="icon_image"]').val('');
            $('.impulse-icon-image-preview').remove();
            $('#impulse-icon-modal').removeData('target').hide();

            

            
            var id = $('.impulse-panel-right').data('element-id');
            if (id) {
                viewportPreserve.capture();
                var settings = collectSettingsFromPanel();
                $.ajax({
                    url: Impulse.api + 'elements/' + id,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: settings, page_id: Impulse.pageId }),
                    success: function() {
                        refreshElement(id);
                    }
                });
            }
        });

        $(document).on('click', '.impulse-collapsible-divider', function(e) {

            

            if (e && e.target && $(e.target).closest('.impulse-color-setting, .impulse-color-swatch, .impulse-color-picker, .impulse-tw-color-wrap').length) return;
            var target = $(this).data('target');
            var $content = $(this).next('.' + target);
            var $arrow = $(this).find('.impulse-collapse-arrow');
            if ($content.is(':visible')) {
                $content.slideUp(150);
                $arrow.css('transform', 'rotate(-90deg)');
            } else {
                $content.slideDown(150);
                $arrow.css('transform', 'rotate(0deg)');
            }
        });

        $(document).on('change', 'input[name="tw_spotlight"]', function() {
            $(this).closest('.impulse-textwall-content').find('.impulse-tw-spot-diam').toggle(this.checked);
        });

        

        $(document).on('change', '.impulse-fit-parent-cb', function() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var collected = (typeof collectSettingsFromPanel === 'function') ? collectSettingsFromPanel(existing) : {};
            collected.fill_container = this.checked ? '1' : '';
            var merged = $.extend({}, existing, collected);
            $('.impulse-panel-right').data('existing-settings', merged);
            if (typeof enqueueSave === 'function') {
                enqueueSave(id, merged, function(ok){ if (ok && typeof refreshElement === 'function') refreshElement(id); });
            }
        });

        

        $(document).on('click', '.impulse-section-tab', function() {
            var tab = $(this).data('stab');
            var $panel = $(this).closest('.impulse-panel-body, .impulse-panel-right');
            
            $(this).siblings('.impulse-section-tab').css({color:'#666','border-bottom-color':'transparent'});
            $(this).css({color:''+ImpC.white+'','border-bottom-color':''+ImpC.white+''});
            
            $panel.find('.impulse-section-tab-content').hide();
            $panel.find('.impulse-section-tab-content[data-stab="' + tab + '"]').show();
        });

        

        
        function _openSectionBgPicker() {
            openImglibPicker({ label: 'Select Background Image' }, function(attachment) {
                $('input[name="bg_image"]').val(attachment.url).trigger('change');

                _autoGenSectionDepth(attachment.url, attachment);
                var previewHtml = '<img src="' + attachment.url + '" class="impulse-bg-image-thumb" style="width:100%;max-height:80px;object-fit:cover;border-radius:4px;display:block">';
                previewHtml += '<button type="button" class="impulse-remove-bg" style="position:absolute;top:4px;right:4px;z-index:2;width:20px;height:20px;border-radius:3px;border:none;background:rgba(0,0,0,0.6);color:'+ImpC.white+';cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove image"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                previewHtml += '<div class="impulse-bg-position-grid" style="position:absolute;top:0;left:0;right:0;bottom:0;display:grid;grid-template-columns:repeat(3,1fr);grid-template-rows:repeat(3,1fr);padding:4px;pointer-events:none">';
                var posMap = [
                    {v:'0% 0%',icon:'<path d="M7 17V7h10"/><path d="M17 17 7 7"/>'},
                    {v:'50% 0%',icon:'<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>'},
                    {v:'100% 0%',icon:'<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'},
                    {v:'0% 50%',icon:'<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>'},
                    {v:'50% 50%',icon:'<path d="m7 20 5-5 5 5"/><path d="m7 4 5 5 5-5"/>'},
                    {v:'100% 50%',icon:'<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>'},
                    {v:'0% 100%',icon:'<path d="M17 7 7 17"/><path d="M17 17H7V7"/>'},
                    {v:'50% 100%',icon:'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'},
                    {v:'100% 100%',icon:'<path d="m7 7 10 10"/><path d="M17 7v10H7"/>'}
                ];
                var alignMap = ['flex-start','center','flex-end'];
                posMap.forEach(function(p, i) {
                    var isActive = p.v === '50% 50%';
                    var row = Math.floor(i / 3), col = i % 3;
                    previewHtml += '<div style="display:flex;align-items:' + alignMap[row] + ';justify-content:' + alignMap[col] + ';pointer-events:auto">';
                    previewHtml += '<button type="button" class="impulse-bg-pos-btn' + (isActive ? ' active' : '') + '" data-pos="' + p.v + '" style="width:18px;height:18px;border-radius:3px;border:none;background:' + (isActive ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.25)') + ';cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center;box-shadow:0 1px 2px rgba(0,0,0,0.3)" title="' + p.v + '"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="' + (isActive ? ''+ImpC.surface2+'' : 'rgba(255,255,255,0.7)') + '" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">' + p.icon + '</svg></button>';
                    previewHtml += '</div>';
                });
                previewHtml += '</div>';
                previewHtml += '<input type="hidden" name="bg_position" value="50% 50%">';
                $('#impulse-section-bg-preview').remove();
                $('input[name="bg_image"]').after('<div id="impulse-section-bg-preview" title="Click to replace" style="position:relative;cursor:pointer">' + previewHtml + '</div>');
                $('.impulse-bg-no-image-row').hide();
                $('.impulse-bg-image-settings').show();
                $('.impulse-overlay-section').show();
                $('.impulse-bg-base-color-wrap').hide();
                autoSaveAndPreview();
            });
        }
        $(document).on('click', '#impulse-select-section-bg', _openSectionBgPicker);

        

        

        
        $(document).on('click', '#impulse-section-bg-preview', function(e) {
            var $t = $(e.target);
            if ($t.closest('.impulse-bg-pos-btn').length) return;
            if ($t.closest('.impulse-remove-bg').length)  return;
            e.preventDefault();
            e.stopPropagation();
            _openSectionBgPicker();
        });

        

        

        

        

        

        
        var _autoDepthInflight = {};
        function _autoGenSectionDepth(imageUrl, attachment) {
            var id = $('.impulse-panel-right').data('element-id');
            if (!imageUrl || !id) return;
            
            if ($('input[name="bg_depth_image"]').val() === imageUrl && $('input[name="bg_depth_map"]').val()) return;
            
            if (attachment && attachment.depthUrl) { _commitSectionBg3d(imageUrl, attachment.depthUrl); return; }

            if (!window.Impulse || !Impulse.isStandalone) return;
            if (_autoDepthInflight[id] === imageUrl) return; 
            _autoDepthInflight[id] = imageUrl;

            

            _depthProgress(true);
            $.ajax({
                url: (Impulse.siteUrl || '') + '/api/depth-map.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    image_url:   imageUrl,
                    license_key: (Impulse && Impulse.licenseKey) || '',
                    nonce:       (Impulse && Impulse.nonce) || ''
                }),
                timeout: 300000,
                success: function(resp) {
                    delete _autoDepthInflight[id];
                    _depthProgress(false);
                    
                    if (resp && resp.success && resp.depth_url && $('input[name="bg_image"]').val() === imageUrl) {
                        _commitSectionBg3d(imageUrl, resp.depth_url);
                    } else if (!resp || !resp.success) {
                        (window.showToast || function(){})('Depth generation failed. Please try again.', 'error');
                    }
                },
                error: function() {
                    delete _autoDepthInflight[id];
                    _depthProgress(false);
                    (window.showToast || function(){})('Depth service unavailable. Please try again.', 'error');
                }
            });
        }

        function _commitSectionBg3d(imageUrl, depthUrl) {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            $('input[name="bg_depth_image"]').val(imageUrl);
            $('input[name="bg_depth_map"]').val(depthUrl);
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var collected = collectSettingsFromPanel(existing);
            collected.bg_depth_image = imageUrl;
            collected.bg_depth_map   = depthUrl;

            

            
            if ((parseInt(collected.bg_depth_strength) || 0) <= 0) {
                collected.bg_depth_strength = 50;
                $('input[name="bg_depth_strength"]').val(50);
            }
            var merged = $.extend({}, existing, collected);
            $('.impulse-panel-right').data('existing-settings', merged);
            enqueueSave(id, merged, function(ok) {
                if (!ok) return;
                showSaveStatus();
                refreshElement(id);   

                

                

                var _mountDepth = function () {
                    var _ifr = document.getElementById('impulse-iframe');
                    var _w   = _ifr && _ifr.contentWindow;
                    if (_w && _w.ImpulseDepthParallax && _w.ImpulseDepthParallax.initAll) {
                        try { _w.ImpulseDepthParallax.initAll(); } catch (_e) {}
                    }
                };
                [500, 1100, 1900, 2800].forEach(function (ms) { setTimeout(_mountDepth, ms); });

                if (window.showToast) window.showToast('3D depth ready — section is now 3D', 'success');

                openSettings(id, selectedElementType || 'section');   
            });
        }

        
        
        function _runDepthGenerateForSection(imageUrl, $btn) {
            if (!imageUrl) return;

            if (!Impulse.isStandalone) {
                (window.showToast || function(){})('Depth map generation is not available in this build.', 'error');
                return;
            }
            if ($btn && $btn.length) $btn.prop('disabled', true).text('Calculating…');
            _depthProgress(true);
            $.ajax({
                url: (Impulse.siteUrl || '') + '/api/depth-map.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    image_url:   imageUrl,
                    license_key: (Impulse && Impulse.licenseKey) || '',
                    nonce:       (Impulse && Impulse.nonce) || ''
                }),
                timeout: 300000,
                success: function(resp) {
                    if ($btn && $btn.length) $btn.prop('disabled', false).text('Convert to 3D');
                    _depthProgress(false);
                    if (!resp || !resp.success || !resp.depth_url) {
                        (window.showToast || function(){})('Depth generation failed: ' + ((resp && resp.error) || 'unknown'), 'error');
                        return;
                    }
                    _commitSectionBg3d(imageUrl, resp.depth_url);
                },
                error: function() {
                    if ($btn && $btn.length) $btn.prop('disabled', false).text('Convert to 3D');
                    _depthProgress(false);
                    (window.showToast || function(){})('Depth service unavailable. Please try again.', 'error');
                }
            });
        }

        function _openSectionBg3dPicker($triggerBtn) {
            openImglibPicker({
                label:            'Select 3D Image',
                platformCategory: '3d',
                noFocal:          true,
                noUpload:         !Impulse.hasActiveLicense
            }, function(attachment) {
                var imageUrl    = attachment && attachment.url;
                var pairedDepth = attachment && attachment.depthUrl;
                if (!imageUrl) return;
                if (pairedDepth) {
                    _commitSectionBg3d(imageUrl, pairedDepth);
                } else {
                    
                    (window.showToast || function(){})('Calculating depth map…', 'info');
                    _runDepthGenerateForSection(imageUrl, $triggerBtn);
                }
            });
        }

        

        
        
        function _countDepthSectionsOnPage() {
            var ifr = document.getElementById('impulse-iframe');
            var doc = ifr && (ifr.contentDocument || ifr.contentWindow.document);
            if (!doc) return 0;
            return doc.querySelectorAll('section.impulse-section[data-depth-image][data-depth-map]').length;
        }

        

        
        var _BG_3D_HARD_CAP = Infinity;  
        var _BG_3D_SOFT_WARN = 6;        

        

        

        

        $(document).on('click', '.impulse-bg-3d-pick', function() {
            var currentBg = ($('input[name="bg_image"]').val() || '').trim();
            if (!currentBg) {
                (window.showToast || function(){})('Pick a background image first, then Convert to 3D.', 'error');
                return;
            }
            var _existing = _countDepthSectionsOnPage();

            

            
            
            if (_existing + 1 > _BG_3D_HARD_CAP) {
                (window.showToast || function(){})(
                    'Limit reached: ' + _BG_3D_HARD_CAP + ' 3D sections per page. Remove one to add another.',
                    'error'
                );
                return;
            }
            if (_existing + 1 >= _BG_3D_SOFT_WARN) {
                (window.showToast || function(){})(
                    '3D sections are WebGL-heavy. Use sparingly on slow devices.',
                    'info'
                );
            } else {
                (window.showToast || function(){})('Calculating depth map…', 'info');
            }
            _runDepthGenerateForSection(currentBg, $(this));
        });

        
        
        $(document).on('click', '.impulse-bg-3d-pick-direct', function() {
            var _existing = _countDepthSectionsOnPage();
            if (_existing + 1 > _BG_3D_HARD_CAP) {
                (window.showToast || function(){})(
                    'Limit reached: ' + _BG_3D_HARD_CAP + ' 3D sections per page. Remove one to add another.',
                    'error'
                );
                return;
            }
            if (_existing + 1 >= _BG_3D_SOFT_WARN) {
                (window.showToast || function(){})(
                    '3D sections are WebGL-heavy. Use sparingly on slow devices.',
                    'info'
                );
            }
            _openSectionBg3dPicker($(this));
        });
        $(document).on('click', '.impulse-bg-3d-change', function() {
            _openSectionBg3dPicker($(this));
        });

        $(document).on('click', '.impulse-bg-3d-remove', function() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            $('input[name="bg_depth_image"]').val('');
            $('input[name="bg_depth_map"]').val('');
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var collected = collectSettingsFromPanel(existing);
            collected.bg_depth_image = '';
            collected.bg_depth_map   = '';
            var merged = $.extend({}, existing, collected);
            $('.impulse-panel-right').data('existing-settings', merged);
            enqueueSave(id, merged, function(ok) {
                if (!ok) return;
                showSaveStatus();
                refreshElement(id);
                openSettings(id, selectedElementType || 'section');   
            });
        });

        $(document).on('click', '.impulse-remove-bg', function() {
            $('input[name="bg_image"]').val('');

            

            

            $('input[name="bg_depth_image"]').val('');
            $('input[name="bg_depth_map"]').val('');
            $('input[name="bg_depth_strength"]').val(0);
            $('#impulse-section-bg-preview').remove();

            $('.impulse-bg-no-image-row').css('display', 'flex');
            $('.impulse-bg-image-settings').hide();
            $('.impulse-overlay-section').hide();
            $('.impulse-bg-base-color-wrap').css('display', 'flex');

            
            
            var _id = $('.impulse-panel-right').data('element-id');
            if (!_id) { autoSaveAndPreview(); return; }
            var _existing = $('.impulse-panel-right').data('existing-settings') || {};
            var _merged = $.extend({}, _existing, collectSettingsFromPanel(_existing));
            _merged.bg_image = '';
            _merged.bg_depth_image = '';
            _merged.bg_depth_map = '';
            _merged.bg_depth_strength = 0;
            $('.impulse-panel-right').data('existing-settings', _merged);
            enqueueSave(_id, _merged, function(ok) {
                if (!ok) return;
                showSaveStatus();
                refreshElement(_id); 
            });
        });

        $(document).on('click', '.impulse-bg-pos-btn', function() {
            var pos = $(this).data('pos');
            $('.impulse-bg-pos-btn').css({background: 'rgba(0,0,0,0.25)'}).removeClass('active').find('svg').attr('stroke', 'rgba(255,255,255,0.7)');
            $(this).css({background: 'rgba(255,255,255,0.85)'}).addClass('active').find('svg').attr('stroke', ''+ImpC.surface2+'');
            $('input[name="bg_position"]').val(pos);
            var id = $('.impulse-panel-right').data('element-id');
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe && iframe.contentDocument;
            if (doc && id) {
                var sectionEl = doc.querySelector('.impulse-el[data-id="' + id + '"] section.impulse-section');
                if (sectionEl) sectionEl.style.backgroundPosition = pos; 

                var _fm = String(pos).match(/(-?[\d.]+)%?\s+(-?[\d.]+)%?/);
                if (_fm && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({ type: 'impulse-depth-focal',
                        x: Math.max(0, Math.min(1, parseFloat(_fm[1]) / 100)),
                        y: Math.max(0, Math.min(1, parseFloat(_fm[2]) / 100)) }, '*');
                }
            }

            
            if (id) {
                var _dev = window.impulseDevice || 'desktop';
                var _saveData = {};
                _saveData[_dev === 'desktop' ? 'bg_position' : 'bg_position_' + _dev] = pos;
                var _existing = $('.impulse-panel-right').data('existing-settings') || {};
                var _merged = $.extend({}, _existing, _saveData);
                $('.impulse-panel-right').data('existing-settings', _merged);
                enqueueSave(id, _merged);
            }
        });

        

        function _overlayRuntimePreview() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            var existing = $('.impulse-panel-right').data('existing-settings') || {};
            var collected = collectSettingsFromPanel(existing);
            var merged = $.extend({}, existing, collected);
            $('.impulse-panel-right').data('existing-settings', merged);
            enqueueSave(id, merged, function(ok) {
                if (ok) { showSaveStatus(); refreshElement(id); }
            });
        }

        
        function _buildEdgeFxCss(fx, pos, bg) {
            var base = 'position:absolute;pointer-events:none;z-index:0;';

            

            
            var edge = 'perimeter';
            if      (pos === 'center-left')   edge = 'right';
            else if (pos === 'center-right')  edge = 'left';
            else if (pos === 'top-center')    edge = 'bottom';
            else if (pos === 'bottom-center') edge = 'top';

            if (fx === 'glow') {

                
                
                if (edge === 'perimeter') {
                    return base + 'inset:0;box-shadow:0 0 60px 8px ' + bg + ',0 0 140px 20px ' + bg + ',inset 0 0 30px rgba(255,255,255,0.12);opacity:0.9;border-radius:inherit;';
                }
                
                var shadowOff = {right:'20px 0 60px 10px', left:'-20px 0 60px 10px', top:'0 -20px 60px 10px', bottom:'0 20px 60px 10px'}[edge];
                return base + 'inset:0;box-shadow:' + shadowOff + ' ' + bg + ';opacity:0.9;border-radius:inherit;';
            }
            if (fx === 'specular') {
                var isVertical = (edge === 'left' || edge === 'right' || edge === 'perimeter');
                var axis = isVertical ? 'Y' : 'X';
                
                var insetPos = {
                    right:      'right:0;top:0;bottom:0;width:2px',
                    left:       'left:0;top:0;bottom:0;width:2px',
                    top:        'top:0;left:0;right:0;height:2px',
                    bottom:     'bottom:0;left:0;right:0;height:2px',
                    perimeter:  'right:0;top:0;bottom:0;width:2px'
                }[edge];
                var stripDir = isVertical ? '180deg' : '270deg';

                
                return base + insetPos + ';overflow:hidden;background-image:linear-gradient(' + stripDir + ',transparent 0%,rgba(255,255,255,0.85) 45%,rgba(255,255,255,1) 50%,rgba(255,255,255,0.85) 55%,transparent 100%);background-size:' + (isVertical ? '100% 40%' : '40% 100%') + ';background-repeat:no-repeat;background-position:' + (isVertical ? '0 -50%' : '-50% 0') + ';animation:impulseOvSpecular' + axis + ' 3s ease-in-out infinite;';
            }
            if (fx === 'caustic') {

                var insetPos2 = {
                    right:      'right:0;top:0;bottom:0;width:40px',
                    left:       'left:0;top:0;bottom:0;width:40px',
                    top:        'top:0;left:0;right:0;height:30px',
                    bottom:     'bottom:0;left:0;right:0;height:30px',
                    perimeter:  'inset:0'
                }[edge];
                return base + insetPos2 + ';background:radial-gradient(circle at 20% 30%,rgba(255,255,255,0.35) 0%,transparent 40%),radial-gradient(circle at 80% 70%,rgba(255,255,255,0.25) 0%,transparent 35%),radial-gradient(circle at 50% 90%,rgba(255,255,255,0.3) 0%,transparent 40%);mix-blend-mode:screen;opacity:0.6;';
            }
            if (fx === 'pressure') {

                
                if (edge === 'perimeter') {
                    return base + 'inset:0;box-shadow:0 30px 90px -10px rgba(0,0,0,0.55),inset 0 1px 0 rgba(255,255,255,0.35);border-radius:inherit;';
                }

                var outerShadow = {right:'30px 0 60px -8px', left:'-30px 0 60px -8px', top:'0 -30px 60px -8px', bottom:'0 30px 60px -8px'}[edge];
                var innerHighlight = {right:'inset -1px 0 0 rgba(255,255,255,0.25)', left:'inset 1px 0 0 rgba(255,255,255,0.25)', top:'inset 0 -1px 0 rgba(255,255,255,0.25)', bottom:'inset 0 1px 0 rgba(255,255,255,0.25)'}[edge];
                return base + 'inset:0;box-shadow:' + outerShadow + ' rgba(0,0,0,0.55),' + innerHighlight + ';border-radius:inherit;';
            }
            return base + 'display:none;';
        }

        
        function _deadScrimPreview() {
            if (true) return;  
            var _ovId = $('.impulse-panel-right').data('element-id');
            if (!_ovId) return;
            
            var _ovExisting = $('.impulse-panel-right').data('existing-settings') || {};
            var _ovCollected = collectSettingsFromPanel(_ovExisting);
            var _ovMerged = $.extend({}, _ovExisting, _ovCollected);
            $('.impulse-panel-right').data('existing-settings', _ovMerged);
            enqueueSave(_ovId, _ovMerged, function(ok) { if (ok) showSaveStatus(); });

            var iframe = document.getElementById('impulse-iframe');
            if (!iframe) return;
            var frameRect = iframe.getBoundingClientRect();

            if (frameRect.width < 50 || frameRect.height < 50) {
                frameRect = { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };
            }

            var pos  = $('input[name="position"]').val()        || 'center';
            var anim = $('input[name="popup_animation"]').val() || 'depth';
            var w = parseInt($('input[name="popup_width"]').val())   || 500;
            var h = parseInt($('input[name="popup_height"]').val())  || 0;
            var pad = parseInt($('input[name="popup_padding"]').val()) || 24;
            var rad = parseInt($('input[name="popup_radius"]').val()) || 8;
            var bg  = $('input[name="popup_bg"]').val()      || '#ffffff';
            var overlayCol = $('input[name="overlay_color"]').val() || 'rgba(0,0,0,0.5)';

            var existing = document.getElementById('impulse-overlay-preview-scrim');
            if (existing && existing.parentNode) existing.parentNode.removeChild(existing);

            
            
            var scrim = document.createElement('div');
            scrim.id = 'impulse-overlay-preview-scrim';

            scrim.style.cssText = 'position:fixed!important;top:' + frameRect.top + 'px!important;left:' + frameRect.left + 'px!important;width:' + frameRect.width + 'px!important;height:' + frameRect.height + 'px!important;z-index:2147483646!important;background:' + overlayCol + '!important;pointer-events:auto!important;overflow:hidden!important;display:block!important;visibility:visible!important;opacity:1!important;transition:opacity 0.3s ease-in-out!important;';
            scrim.addEventListener('click', function(ev) {
                if (ev.target === scrim) {
                    scrim.style.opacity = '0';
                    setTimeout(function() { if (scrim.parentNode) scrim.parentNode.removeChild(scrim); }, 300);
                }
            });

            var fw = frameRect.width, fh = frameRect.height;
            var cont = document.createElement('div');
            var contPos, sizeCss, radiusCss;
            var _w = Math.min(w, fw - 32);

            
            
            var _bannerMax = Math.max(160, Math.round(fh * 0.5));
            if (pos === 'center') {
                contPos = 'top:50%;left:50%;transform:translate(-50%,-50%)';
                sizeCss = 'width:' + _w + 'px;max-width:' + (fw - 32) + 'px;max-height:' + (fh - 32) + 'px;';
                radiusCss = 'border-radius:' + rad + 'px;';
            } else if (pos === 'center-left') {
                contPos = 'top:0;left:0';
                sizeCss = 'width:' + _w + 'px;max-width:100%;height:' + fh + 'px;';
                radiusCss = 'border-radius:0 ' + rad + 'px ' + rad + 'px 0;';
            } else if (pos === 'center-right') {
                contPos = 'top:0;right:0';
                sizeCss = 'width:' + _w + 'px;max-width:100%;height:' + fh + 'px;';
                radiusCss = 'border-radius:' + rad + 'px 0 0 ' + rad + 'px;';
            } else if (pos === 'top-center') {
                contPos = 'top:0;left:0';
                sizeCss = 'width:100%;' + (h > 0 ? 'height:' + Math.min(h, _bannerMax) + 'px;' : 'min-height:200px;') + 'max-height:' + _bannerMax + 'px;';
                radiusCss = 'border-radius:0 0 ' + rad + 'px ' + rad + 'px;';
            } else if (pos === 'bottom-center') {
                contPos = 'bottom:0;left:0';
                sizeCss = 'width:100%;' + (h > 0 ? 'height:' + Math.min(h, _bannerMax) + 'px;' : 'min-height:200px;') + 'max-height:' + _bannerMax + 'px;';
                radiusCss = 'border-radius:' + rad + 'px ' + rad + 'px 0 0;';
            } else {
                contPos = 'top:50%;left:50%;transform:translate(-50%,-50%)';
                sizeCss = 'width:' + _w + 'px;';
                radiusCss = 'border-radius:' + rad + 'px;';
            }

            
            cont.style.cssText = 'position:absolute!important;' + contPos + '!important;' + sizeCss.replace(/;/g, '!important;') + 'background:' + bg + '!important;background-color:' + bg + '!important;' + radiusCss + 'padding:' + pad + 'px!important;box-sizing:border-box!important;border:none!important;outline:none!important;box-shadow:none!important;filter:none;opacity:0;display:block!important;overflow-y:auto!important;visibility:visible!important;color:#1d2327!important;font:14px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif!important;';

            
            var _popupContent = null;
            try {
                var _ifrDoc = iframe.contentDocument;
                var _popupEl = _ifrDoc && _ifrDoc.querySelector('.impulse-el[data-id="' + _ovId + '"] .impulse-modal-content');
                if (_popupEl) {
                    var _realChildren = _popupEl.querySelectorAll(':scope > .impulse-el');
                    if (_realChildren.length) {
                        _popupContent = _ifrDoc.createElement('div');
                        _popupContent.style.cssText = 'display:flex;flex-direction:column;gap:8px';
                        _realChildren.forEach(function(child) {
                            var c = child.cloneNode(true);
                            
                            c.querySelectorAll('.impulse-el-toolbar, .impulse-dropzone, .impulse-modal-dropzone').forEach(function(n) { n.remove(); });
                            c.classList.remove('selected');
                            _popupContent.appendChild(c);
                        });
                    }
                }
            } catch(_e) {  }
            if (_popupContent) {
                cont.appendChild(_popupContent);
            } else {
                var _ph = document.createElement('div');
                _ph.style.cssText = 'color:#999;text-align:center;padding:16px;font-size:13px';
                _ph.textContent = 'Modal is empty — drop blocks inside to see them here.';
                cont.appendChild(_ph);
            }
            
            var edgeFx = $('input[name="overlay_edge_effect"]').val() || 'none';
            if (edgeFx !== 'none') {
                var fx = document.createElement('div');
                fx.className = 'impulse-ov-edge-fx';
                fx.style.cssText = _buildEdgeFxCss(edgeFx, pos, bg);
                cont.insertBefore(fx, cont.firstChild);
                
                if (edgeFx === 'specular' && !document.getElementById('impulse-ov-specular-css')) {
                    var ks = document.createElement('style');
                    ks.id = 'impulse-ov-specular-css';

                    ks.textContent = '@keyframes impulseOvSpecularY{0%{background-position:0 -50%}100%{background-position:0 150%}}@keyframes impulseOvSpecularX{0%{background-position:-50% 0}100%{background-position:150% 0}}';
                    document.head.appendChild(ks);
                }
            }
            scrim.appendChild(cont);
            (document.documentElement || document.body).appendChild(scrim);

            var edges = ['top-center','bottom-center','center-left','center-right'];
            var isEdge = edges.indexOf(pos) !== -1;
            var cp = (pos === 'center') ? 'translate(-50%,-50%) ' : '';

            
            var hT, hF = '';
            if      (anim === 'depth') {
                
                hT = 'perspective(900px) translateZ(-1400px) scale(0.35) rotateX(6deg)';
                hF = 'blur(22px) brightness(0.6)';
            }
            else if (anim === 'tilt-fall') {
                
                hT = 'perspective(900px) rotateZ(-28deg) rotateX(35deg) translateY(-140%) translateZ(-200px)';
                hF = 'blur(4px)';
            }
            else if (anim === 'glass') {
                
                hT = 'perspective(1600px) scale(1.25) rotateX(-8deg)';
                hF = 'blur(40px) saturate(1.6) brightness(1.1)';
            }
            else  {
                
                hT = 'perspective(900px) rotateY(-35deg) rotateX(18deg) translateZ(-300px) translateX(-80px)';
                hF = 'blur(8px)';
            }
            cont.style.transform = cp + hT;
            cont.style.filter = hF;

            var vT = isEdge ? 'translate(0,0)' : 'translate(-50%,-50%) scale(1)';

            
            var curve;
            if      (anim === 'tilt-fall') curve = 'cubic-bezier(0.34,1.70,0.64,1)';
            else if (anim === 'depth')     curve = 'cubic-bezier(0.16,1.15,0.30,1)';
            else if (anim === 'glass')     curve = 'cubic-bezier(0.4, 0, 0.2, 1)';
            else                           curve = 'cubic-bezier(0.25,0.46,0.30,1.05)';

            var shown = false;
            function show() {
                if (shown) return; shown = true;
                scrim.style.opacity = '1';

                var dur = anim === 'depth' ? '1.4s' : (anim === 'tilt-fall' ? '1.3s' : '1.15s');
                cont.style.transition = 'transform ' + dur + ' ' + curve + ', filter 1.1s ease-in-out, opacity 0.8s ease-in-out';
                cont.style.transform = vT;
                cont.style.filter = '';
                cont.style.opacity = '1';

                
                if (anim === 'parallax' && !isEdge) {
                    var pxT = 0, pyT = 0, pxC = 0, pyC = 0, pxRaf = null;
                    function pxTick() {
                        pxC += (pxT - pxC) * 0.12;
                        pyC += (pyT - pyC) * 0.12;
                        cont.style.transform = 'translate(-50%,-50%) perspective(900px) rotateY(' + (pxC * 12).toFixed(2) + 'deg) rotateX(' + (-pyC * 12).toFixed(2) + 'deg)';
                        if (Math.abs(pxT - pxC) > 0.005 || Math.abs(pyT - pyC) > 0.005) pxRaf = requestAnimationFrame(pxTick);
                        else pxRaf = null;
                    }
                    scrim._pxHandler = function(ev) {
                        var r = scrim.getBoundingClientRect();
                        pxT = Math.max(-1, Math.min(1, (ev.clientX - r.left) / r.width * 2 - 1));
                        pyT = Math.max(-1, Math.min(1, (ev.clientY - r.top) / r.height * 2 - 1));
                        if (!pxRaf) pxRaf = requestAnimationFrame(pxTick);
                    };
                    document.addEventListener('mousemove', scrim._pxHandler);
                }
            }
            requestAnimationFrame(show);
            setTimeout(show, 100);

            setTimeout(function() {
                scrim.style.opacity = '0';
                if (scrim._pxHandler) document.removeEventListener('mousemove', scrim._pxHandler);
                setTimeout(function() { if (scrim.parentNode) scrim.parentNode.removeChild(scrim); }, 400);
            }, 4200);
        }

        
        
        $(document).on('click', '.impulse-align-grid[data-name="overlay_position_grid"] .impulse-align-dot', function(ev) {
            ev.stopPropagation();
            var $dot = $(this);
            var pos = $dot.data('pos');
            if (!pos) return;
            $dot.closest('.impulse-align-grid').find('.impulse-align-dot').removeClass('active');
            $dot.addClass('active');
            $('input[name="position"]').val(pos);
            _overlayRuntimePreview();
            
            var _ovId = $('.impulse-panel-right').data('element-id');
            if (_ovId) {
                setTimeout(function() {
                    var cachedSettings = $('.impulse-panel-right').data('existing-settings');
                    if (cachedSettings) renderSettingsPanel('modal', cachedSettings);
                }, 350);
            }
            return false;
        });
        
        $(document).on('click', '.impulse-btn-group[data-name="popup_animation"] button, .impulse-btn-group[data-name="overlay_edge_effect"] button', function() {
            setTimeout(_overlayRuntimePreview, 0);
        });

        $(document).on('click', '.impulse-align-dot', function() {
            var $dot = $(this);
            
            if ($dot.closest('.impulse-align-grid').attr('data-name') === 'overlay_position_grid') return;

            if ($dot.attr('data-target') === 'image') return;
            var ca = $dot.data('ca');
            var va = $dot.data('va');

            var _alignDevSfx = (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '';
            $('input[name="content_align' + _alignDevSfx + '"]').val(ca);
            $('input[name="valign' + _alignDevSfx + '"]').val(va);
            
            $('.impulse-align-dot').removeClass('active col-active');
            $dot.addClass('active');
            
            $('.impulse-spread-btn').removeClass('active').css({background:''+ImpC.panel+'',color:''+ImpC.muted+''});
            
            var id = $('.impulse-panel-right').data('element-id');
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe && iframe.contentDocument;
            if (doc && id) {
                var container = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-container');
                var section = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-section');
                if (container) {
                    var marginMap = { left: ['0', 'auto'], center: ['auto', 'auto'], right: ['auto', '0'] };
                    var m = marginMap[ca] || marginMap.center;
                    container.style.marginLeft = m[0];
                    container.style.marginRight = m[1];
                    var valignMap = {top:'flex-start',center:'center',bottom:'flex-end',between:'space-between',around:'space-around',evenly:'space-evenly'};
                    container.style.justifyContent = valignMap[va] || 'center';
                }
                if (section) {
                    var caMap = { left: 'flex-start', center: 'center', right: 'flex-end' };
                    section.style.setProperty('--impulse-ca', caMap[ca] || 'center');
                }
            }
            autoSaveAndPreview(true);
        });

        
        
        $(document).on('click', '.impulse-spread-btn', function() {
            var $btn = $(this);
            var isActive = $btn.hasClass('active');
            var _spreadDevSfx = (window.impulseDevice && window.impulseDevice !== 'desktop') ? '_' + window.impulseDevice : '';
            var ca = $('input[name="content_align' + _spreadDevSfx + '"]').val() || 'center';
            var _vKey = 'valign' + _spreadDevSfx;
            var _pKey = 'valign_prev' + _spreadDevSfx;   
            var _spreadVals = { between: 1, around: 1, evenly: 1 };
            var _exSpread = $('.impulse-panel-right').data('existing-settings') || {};
            var _spreadSave = {};
            var _targetVA;
            if (isActive) {

                var _restore = _exSpread[_pKey] || 'center';
                if (_spreadVals[_restore]) _restore = 'center';
                _targetVA = _restore;
                $btn.removeClass('active').css({background:''+ImpC.panel+'',color:''+ImpC.muted+''});
                $('input[name="' + _vKey + '"]').val(_targetVA);
                $('.impulse-align-dot').removeClass('active col-active');
                $('.impulse-align-dot[data-ca="' + ca + '"][data-va="' + _targetVA + '"]').addClass('active');
                _spreadSave[_vKey] = _targetVA;
                _exSpread[_vKey] = _targetVA;
            } else {

                var _prevVA = $('input[name="' + _vKey + '"]').val() || 'center';
                if (_spreadVals[_prevVA]) _prevVA = 'center';
                _targetVA = 'between';
                $btn.addClass('active').css({background:''+ImpC.white+'',color:''+ImpC.surface2+''});
                $('input[name="' + _vKey + '"]').val(_targetVA);
                $('.impulse-align-dot').removeClass('active col-active');
                $('.impulse-align-dot[data-ca="' + ca + '"]').addClass('col-active');
                _spreadSave[_vKey] = _targetVA;
                _spreadSave[_pKey] = _prevVA;
                _exSpread[_vKey] = _targetVA;
                _exSpread[_pKey] = _prevVA;
            }
            
            $('.impulse-panel-right').data('existing-settings', _exSpread);

            
            var id = $('.impulse-panel-right').data('element-id');
            var iframe = document.getElementById('impulse-iframe');
            var doc = iframe && iframe.contentDocument;
            if (doc && id) {
                var container = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-container');
                if (container) {
                    var _jcMap = { top:'flex-start', center:'center', bottom:'flex-end', between:'space-between', around:'space-around', evenly:'space-evenly' };
                    container.style.justifyContent = _jcMap[_targetVA] || 'center';
                }
            }

            

            
            
            if (id) {
                enqueueSave(id, _spreadSave, function() {
                    if (typeof refreshElement === 'function') refreshElement(id);
                });
            }
        });

        $(document).on('click', '.impulse-select-image-btn[data-name="cell_bg_image"]', function(e) {
            e.stopImmediatePropagation();
            
            if (selectedElementType !== 'rows' && selectedElementType !== 'columns') return;
            var selected = getSelectedCellGridCells();
            if (selected.length !== 1) return;
            
            openImglibPicker({ label: 'Select Cell Image' }, function(attachment) {
                $('input[name="cell_bg_image"]').val(attachment.url);
                $('.impulse-cell-bg-color-row').attr('style', 'display:none');
                $('.impulse-cell-select-image-row').attr('style', 'display:none');
                var $imageOptions = $('.impulse-cell-image-options');
                $imageOptions.attr('style', '');
                if ($imageOptions.find('.impulse-image-preview').length === 0) {
                    var previewHtml = '<div class="impulse-image-preview" style="margin-top:8px">';
                    previewHtml += '<img src="' + attachment.url + '" style="max-width:100%;max-height:60px;border-radius:4px">';
                    previewHtml += '<button type="button" class="impulse-remove-image-btn" data-name="cell_bg_image" style="display:block;margin-top:4px;font-size:11px;color:#888;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';padding:4px 8px;border-radius:3px;cursor:pointer">Remove</button>';
                    previewHtml += '</div>';
                    $imageOptions.prepend(previewHtml);
                } else {
                    $imageOptions.find('.impulse-image-preview img').attr('src', attachment.url);
                }
                withSelectedCellData(function(cell) { cell.bg_image = attachment.url; }, true);
            });
        });

        $(document).on('click', '.impulse-select-image-btn', function() {
            var inputName = $(this).data('name');
            var $btn = $(this);
            openImglibPicker({ label: 'Select Image' }, function(attachment) {
                var $container = $btn.closest('.impulse-image-setting');
                $container.find('input[name="' + inputName + '"]').val(attachment.url).trigger('change');
                if (inputName === 'logo' && (selectedElementType === 'header' || selectedElementType === 'footer')) {
                    $container.html(
                        '<input type="hidden" name="logo" value="' + attachment.url + '">' +
                        '<div style="display:flex;align-items:center;gap:6px">' +
                        '<img src="' + attachment.url + '" class="impulse-logo-preview impulse-select-image-btn" data-name="logo" style="height:40px;width:auto;border-radius:3px;cursor:pointer;border:1px solid '+ImpC.border+'">' +
                        '<button type="button" class="impulse-remove-image-btn" data-name="logo" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove logo"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>' +
                        '</div>'
                    );
                    autoSaveAndRefresh();
                    return;
                }
                $container.find('.impulse-image-preview').remove();
                $container.find('.impulse-select-image-btn').hide();
                $container.append('<div class="impulse-image-preview"><button type="button" class="impulse-remove-image-btn" data-name="' + inputName + '" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button></div>');
                if (inputName === 'la_image_src') {
                    var _svgUrl = attachment.url || '';
                    var _isSvgSel = /\.svg(\?|$)/i.test(_svgUrl);
                    
                    var _selId0 = $('.impulse-panel-right').data('element-id');
                    var _selEx0 = $('.impulse-panel-right').data('existing-settings') || {};
                    var _selS0  = collectSettingsFromPanel(_selEx0);
                    var _selM0  = $.extend({}, _selEx0, _selS0);
                    $('.impulse-panel-right').data('existing-settings', _selM0);
                    $('#impulse-settings-body').html(buildSettingsForm('title', _selM0, []));
                impulseAnimatorSvgAutoLoad();
                    enqueueSave(_selId0, _selM0, function(ok) { if (ok) refreshElement(_selId0); });
                    if (_isSvgSel) {
                        
                        fetch(_svgUrl)
                            .then(function(r) { return r.text(); })
                            .then(function(svgText) {
                                var found = {};
                                function _addColor(v) {
                                    v = v.trim().toLowerCase();
                                    if (!v || v === 'none' || v === 'transparent' || v === 'inherit' || v === 'currentcolor' || v.startsWith('url(')) return;
                                    found[v] = v;
                                }
                                
                                var _re1 = /(?:fill|stroke|stop-color)=["']([^"']+)["']/gi, mv;
                                while ((mv = _re1.exec(svgText)) !== null) _addColor(mv[1]);
                                
                                var _re2 = /(?:fill|stroke|stop-color|color)\s*:\s*([^;}'"<\s]+)/gi;
                                while ((mv = _re2.exec(svgText)) !== null) _addColor(mv[1]);
                                if (!Object.keys(found).length) return; 
                                var colorJson = JSON.stringify(found);
                                
                                $('input[name="la_svg_colors"]').val(colorJson);
                                var _selId2 = $('.impulse-panel-right').data('element-id');
                                var _selEx2 = $('.impulse-panel-right').data('existing-settings') || {};
                                var _selS2  = collectSettingsFromPanel(_selEx2);
                                var _selM2  = $.extend({}, _selEx2, _selS2);
                                $('.impulse-panel-right').data('existing-settings', _selM2);
                                $('#impulse-settings-body').html(buildSettingsForm('title', _selM2, []));
                impulseAnimatorSvgAutoLoad();
                                enqueueSave(_selId2, _selM2, null);
                            })
                            .catch(function() {}); 
                    }
                } else { autoSaveAndPreview(); }
            });
        });

        $(document).on('click', '.impulse-remove-image-btn[data-name="cell_bg_image"]', function(e) {
            e.stopImmediatePropagation();
            e.preventDefault();
            
            if (selectedElementType !== 'rows' && selectedElementType !== 'columns') return;
            var selected = getSelectedCellGridCells();
            if (selected.length !== 1) return;

            $('input[name="cell_bg_image"]').val('');

            $('.impulse-cell-bg-color-row').attr('style', 'display:flex;align-items:center;gap:6px');

            $('.impulse-cell-select-image-row').attr('style', 'display:block;margin-left:auto');

            $('.impulse-cell-image-options').attr('style', 'display:none');
            $('.impulse-cell-image-options .impulse-image-preview').remove();

            $('.impulse-btn-group[data-name="cell_bg_fit"] button').removeClass('active');
            $('.impulse-btn-group[data-name="cell_bg_fit"] button[data-value="cover"]').addClass('active');
            $('input[name="cell_bg_fit"]').val('cover');
            
            $('.impulse-btn-group[data-name="cell_bg_position"] button').removeClass('active');
            $('.impulse-btn-group[data-name="cell_bg_position"] button[data-value="center"]').addClass('active');
            $('input[name="cell_bg_position"]').val('center');

            withSelectedCellData(function(cell) {
                cell.bg_image = '';
                cell.bg_fit = 'cover';
                cell.bg_position = 'center';
            }, true);
        });

        $(document).on('click', '.impulse-remove-image-btn', function() {
            var inputName = $(this).data('name');
            var $container = $(this).closest('.impulse-image-setting');
            $container.find('input[name="' + inputName + '"]').val('').trigger('change');
            
            if (inputName === 'logo' && (selectedElementType === 'header' || selectedElementType === 'footer')) {
                $container.html(
                    '<input type="hidden" name="logo" value="">' +
                    '<button type="button" class="instinctor-btn impulse-select-image-btn" data-name="logo" style="height:26px">Select Logo</button>'
                );
                autoSaveAndRefresh();
                return;
            }
            $container.find('.impulse-image-preview').remove();
            $container.find('.impulse-select-image-btn').show();
            if (inputName === 'la_image_src') {
                
                $container.closest('.impulse-setting-row, .la-image-settings').siblings().find('input[name="la_svg_colors"]').val('');
                $('input[name="la_svg_colors"]').val('');
                
                var _rmId = $('.impulse-panel-right').data('element-id');
                var _rmExist = $('.impulse-panel-right').data('existing-settings') || {};
                var _rmSettings = collectSettingsFromPanel(_rmExist);
                var _rmMerged = $.extend({}, _rmExist, _rmSettings);
                
                $('.impulse-panel-right').data('existing-settings', _rmMerged);
                $('#impulse-settings-body').html(buildSettingsForm('title', _rmMerged, []));
                impulseAnimatorSvgAutoLoad();
                enqueueSave(_rmId, _rmMerged, function(ok) {
                    if (ok) refreshElement(_rmId);
                });
            } else { autoSaveAndPreview(); }
        });

        

        
        var currentBadgeItem = null;

        $(document).on('click', '.impulse-badge-header', function(e) {
            
            if ($(e.target).closest('.impulse-badge-remove').length) return;
            $(this).closest('.impulse-trust-badge-item').toggleClass('collapsed');
        });

        $(document).on('click', '.impulse-badge-remove', function(e) {
            e.stopPropagation();
            $(this).closest('.impulse-trust-badge-item').remove();
            saveBadgesAndPreview();
        });

        $(document).on('click', '.impulse-badge-select-icon', function() {
            currentBadgeItem = $(this).closest('.impulse-trust-badge-item');
            loadIcons();
            $('#impulse-icon-modal').data('target', 'badge').show();
        });

        
        
        $(document).on('input', '.impulse-badge-text', function() {
            var $item = $(this).closest('.impulse-trust-badge-item');
            var text = $(this).val() || 'Badge';
            $item.find('.impulse-badge-label').text(text);
            saveBadgesAndPreview();
        });

        $(document).on('input', '.impulse-badge-color-picker', function() {
            var $item = $(this).closest('.impulse-trust-badge-item');
            var color = $(this).val();
            $item.find('.impulse-badge-color-hex').val(color);

            var svg = $item.find('.impulse-badge-svg').val();
            if (!svg) {
                $item.find('.impulse-badge-preview').css('color', color);
            }
            
            saveBadgesAndPreview();
        });

        $(document).on('input', '.impulse-badge-color-hex', function() {
            var $item = $(this).closest('.impulse-trust-badge-item');
            var color = $(this).val();

            if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
                $item.find('.impulse-badge-color-picker').val(color);

                var svg = $item.find('.impulse-badge-svg').val();
                if (!svg) {
                    $item.find('.impulse-badge-preview').css('color', color);
                }
                
                saveBadgesAndPreview();
            }
        });

        function saveBadgesAndPreview() {
            var badges = [];
            $('.impulse-trust-badges-list .impulse-trust-badge-item').each(function() {
                badges.push({
                    icon: $(this).find('.impulse-badge-icon').val() || 'shield',
                    svg: $(this).find('.impulse-badge-svg').val() || '',
                    text: $(this).find('.impulse-badge-text').val() || '',
                    color: $(this).find('.impulse-badge-color-picker').val() || $(this).find('.impulse-badge-color-hex').val() || '#666666'
                });
            });

            var $hiddenInput = $('#impulse-settings-panel, #impulse-settings-body').find('input[name="badges"]');
            if (!$hiddenInput.length) {
                $('#impulse-settings-body').append('<input type="hidden" name="badges" value="">');
                $hiddenInput = $('#impulse-settings-body').find('input[name="badges"]');
            }
            $hiddenInput.val(JSON.stringify(badges));
            
            autoSaveAndPreview();
        }

        $(document).on('click', '#impulse-add-form-field', function() {
            var $list = $('.impulse-form-fields-list');
            var idx = $list.find('.impulse-form-field-item').length;
            var newField = {
                type: 'text',
                label: 'New Field',
                name: 'field_' + idx,
                placeholder: '',
                required: false,
                width: 'full'
            };
            
            var _ft = [{v:'text',l:'Text'},{v:'email',l:'Email'},{v:'phone',l:'Phone'},{v:'number',l:'Number'},{v:'textarea',l:'Textarea'},{v:'select',l:'Dropdown'},{v:'checkbox',l:'Checkbox'}];
            var html = '<div class="impulse-form-field-item" data-field-type="text" data-index="' + idx + '"';
            html += ' data-required="0" data-enabled="1"';
            html += ' data-name="field_' + idx + '" data-placeholder="" draggable="true">';
            html += '<select class="impulse-form-field-type-select" title="Type" style="height:26px;padding:0 4px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;color:'+ImpC.text+';font-size:11px;flex-shrink:0">';
            _ft.forEach(function(t){ html += '<option value="' + t.v + '">' + t.l + '</option>'; });
            html += '</select>';
            html += '<input type="text" class="impulse-form-field-label" value="New Field">';
            html += '<label class="impulse-field-required-toggle" title="Required">';
            html += '<input type="checkbox" class="impulse-field-required-cb">';
            html += '</label>';
            html += '</div>';
            
            $list.append(html);
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });

        $(document).on('change', '.impulse-form-field-label', function() {
            var $item = $(this).closest('.impulse-form-field-item');
            var newLabel = $(this).val();
            
            $item.data('name', newLabel.toLowerCase().replace(/[^a-z0-9]/g, '_'));
            updateFormFieldsJSON();
            autoSaveAndRefresh();
        });

        function saveFormFieldsAndPreview() {
            var fields = [];
            $('.impulse-form-fields-list .impulse-form-field-item').each(function(idx) {
                var fieldData = JSON.parse($(this).find('.impulse-field-data').val() || '{}');
                if (fieldData.label) {
                    fields.push(fieldData);
                }
            });

            var $hiddenInput = $('#impulse-settings-panel, #impulse-settings-body').find('input[name="fields"]');
            if (!$hiddenInput.length) {
                $('#impulse-settings-body').append('<input type="hidden" name="fields" value="">');
                $hiddenInput = $('#impulse-settings-body').find('input[name="fields"]');
            }
            $hiddenInput.val(JSON.stringify(fields));

            var id = $('.impulse-panel-right').data('element-id');
            if (!id) return;
            
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            var settings = collectSettingsFromPanel(existingSettings);
            var mergedSettings = $.extend({}, existingSettings, settings);

            $('.impulse-panel-right').data('existing-settings', mergedSettings);

            $.ajax({
                url: Impulse.api + 'elements/' + id,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                success: function() {
                    refreshPreview();
                }
            });
        }

        var formFieldsSortable = null;
        function initFormFieldsSortable() {
            var formFieldsList = document.querySelector('.impulse-form-fields-list');
            if (formFieldsList && typeof Sortable !== 'undefined') {
                if (formFieldsSortable) {
                    formFieldsSortable.destroy();
                }
                formFieldsSortable = new Sortable(formFieldsList, {

                    filter: 'input, select, label, .impulse-field-required-toggle',
                    preventOnFilter: false,
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    dragClass: 'sortable-drag',
                    onEnd: function() {
                        updateFormFieldsJSON();
                        autoSaveAndRefresh();
                    }
                });
            }
        }

        var formFieldsObserver = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if (node.classList && node.classList.contains('impulse-form-fields-list')) {
                            initFormFieldsSortable();
                        } else if (node.querySelector && node.querySelector('.impulse-form-fields-list')) {
                            initFormFieldsSortable();
                        }
                    }
                });
            });
        });
        formFieldsObserver.observe(document.body, { childList: true, subtree: true });

        
        
        $('#impulse-preview').off('click.imppreview').on('click.imppreview', function() {
            var previewUrl = window.Impulse.siteUrl + '?impulse_preview=' + Impulse.pageId;
            window.open(previewUrl, '_blank');
        });

        $('.impulse-search').on('input', function() {
            var search = $(this).val().toLowerCase();
            $('.impulse-block').each(function() {
                var label = $(this).find('span').text().toLowerCase();
                var type = $(this).data('element').toLowerCase();
                $(this).toggle(label.indexOf(search) > -1 || type.indexOf(search) > -1);
            });

            $('.impulse-block-category').each(function() {
                var hasVisible = $(this).find('.impulse-block:visible').length > 0;
                $(this).toggle(hasVisible);
            });
        });

        function collectPriceListItems() {
            var items = [];
            $('.impulse-pl-items .impulse-pl-item').each(function() {
                items.push({
                    title: $(this).find('[data-field="title"]').val() || '',
                    desc: $(this).find('[data-field="desc"]').val() || '',
                    price: $(this).find('[data-field="price"]').val() || '',
                    icon: $(this).data('icon') || 'circle'
                });
            });
            $('input[name="pl_items"]').val(JSON.stringify(items));
        }

        var formFieldsSortable = null;
        function initFormFieldsSortable() {
            var formFieldsList = document.querySelector('.impulse-form-fields-list');
            if (formFieldsList && typeof Sortable !== 'undefined') {
                if (formFieldsSortable) {
                    formFieldsSortable.destroy();
                }
                formFieldsSortable = new Sortable(formFieldsList, {

                    filter: 'input, select, label, .impulse-field-required-toggle',
                    preventOnFilter: false,
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    dragClass: 'sortable-drag',
                    onEnd: function() {
                        updateFormFieldsJSON();
                        autoSaveAndRefresh();
                    }
                });
            }
        }

        var formFieldsObserver = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if (node.classList && node.classList.contains('impulse-form-fields-list')) {
                            initFormFieldsSortable();
                        } else if (node.querySelector && node.querySelector('.impulse-form-fields-list')) {
                            initFormFieldsSortable();
                        }
                    }
                });
            });
        });
        formFieldsObserver.observe(document.body, { childList: true, subtree: true });

        
        
        $('#impulse-preview').off('click.imppreview').on('click.imppreview', function() {
            var previewUrl = window.Impulse.siteUrl + '?impulse_preview=' + Impulse.pageId;
            window.open(previewUrl, '_blank');
        });

        $('.impulse-search').on('input', function() {
            var search = $(this).val().toLowerCase();
            $('.impulse-block').each(function() {
                var label = $(this).find('span').text().toLowerCase();
                var type = $(this).data('element').toLowerCase();
                $(this).toggle(label.indexOf(search) > -1 || type.indexOf(search) > -1);
            });

            $('.impulse-block-category').each(function() {
                var hasVisible = $(this).find('.impulse-block:visible').length > 0;
                $(this).toggle(hasVisible);
            });
        });

        function collectPriceListItems() {
            var items = [];
            $('.impulse-pl-items .impulse-pl-item').each(function() {
                items.push({
                    title: $(this).find('[data-field="title"]').val() || '',
                    desc: $(this).find('[data-field="desc"]').val() || '',
                    price: $(this).find('[data-field="price"]').val() || '',
                    icon: $(this).data('icon') || 'circle'
                });
            });
            $('input[name="pl_items"]').val(JSON.stringify(items));
        }

        $(document).on('click', '.impulse-pl-add', function() {
            var i = $('.impulse-pl-items .impulse-pl-item').length;
            var html = '<div class="impulse-pl-item" data-index="' + i + '" data-icon="circle" style="margin-bottom:10px">';
            html += '<div style="display:flex;gap:5px;align-items:center">';
            html += '<span class="impulse-pl-drag" style="cursor: default;padding:2px;color:#666"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
            html += '<button type="button" class="impulse-pl-icon-btn" data-index="' + i + '" style="width:26px;height:26px;padding:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:'+ImpC.muted+';flex-shrink:0;box-sizing:border-box;position:relative">' + lucideSvg('circle', 12) + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span></button>';
            html += '<input type="text" data-field="title" value="" placeholder="Item name" style="flex:1;min-width:0;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box">';
            html += '<input type="text" data-field="price" value="" placeholder="$0" style="width:38px;height:26px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;color:'+ImpC.text+';box-sizing:border-box;text-align:right">';
            html += '<button type="button" class="impulse-pl-remove" style="width:26px;flex-shrink:0;height:26px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
            html += '</div>';
            html += '<input type="text" data-field="desc" data-index="' + i + '" value="" placeholder="Description (optional)" style="width:100%;height:22px;padding:0 6px;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;font-size:10px;color:#888;box-sizing:border-box;margin-top:5px">';
            html += '</div>';
            $('.impulse-pl-items').append(html);
            collectPriceListItems();
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-pl-remove', function(e) {
            e.stopPropagation();
            $(this).closest('.impulse-pl-item').remove();
            
            $('.impulse-pl-items .impulse-pl-item').each(function(i) {
                $(this).data('index', i).attr('data-index', i);
                $(this).find('[data-index]').data('index', i).attr('data-index', i);
                $(this).find('.impulse-pl-icon-btn').data('index', i).attr('data-index', i);
            });
            collectPriceListItems();
            autoSaveAndRefresh();
        });

        $(document).on('input', '.impulse-pl-items [data-field]', function() {
            collectPriceListItems();
            autoSaveAndRefresh();
        });

        $(document).on('click', '.impulse-pl-icon-btn', function(e) {
            
            if ($(e.target).hasClass('impulse-icon-copy-down')) return;
            e.preventDefault();
            e.stopPropagation();
            var $btn = $(this);
            loadIcons();
            $('#impulse-icon-modal').data('target', 'price_list_item').data('pl-icon-btn', $btn).show();
        });

        $(document).on('click', '.impulse-pl-icon-btn .impulse-icon-copy-down', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $currentItem = $(this).closest('.impulse-pl-item');
            var $nextItem = $currentItem.next('.impulse-pl-item');
            if (!$nextItem.length) return;
            
            var icon = $currentItem.data('icon') || 'circle';
            $nextItem.data('icon', icon).attr('data-icon', icon);
            var iconHTML = icon === 'none' ? '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="#666" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>' : lucideSvg(icon, 12);
            $nextItem.find('.impulse-pl-icon-btn').html(iconHTML + '<span class="impulse-icon-copy-down" title="Copy icon to next row"></span>');
            collectPriceListItems();
            autoSaveAndRefresh();
        });

        
        var _chartPalettes = {
            pastel:  ['#9CC3E3','#B8D9B0','#F3B48A','#CDB3D4','#2E5C8A','#6FB38F','#E87E77','#D9C38F'],
            muted:   ['#8897A8','#A69F88','#B8A097','#8E9A8A','#556573','#7D786C','#92877B','#A5907D'],
            vibrant: ['#3B82F6','#10B981','#F59E0B','#EC4899','#8B5CF6','#EF4444','#14B8A6','#F97316'],
            mono:    ['#1D2327','#4A4E53','#737780','#9DA2A9','#C6CAD0','#E5E7EA','#3A3F44','#B1B5BB'],
            earth:   ['#8B6F47','#A89078','#C4A57B','#6B4F3A','#9C8168','#5E4A35','#8D7559','#AE9277'],
            ocean:   ['#4EB1BF','#70C8D9','#1B7A8C','#A9DEE6','#0E5F70','#93D2DD','#2F96A8','#BCE5ED']
        };
        function collectChartEntries() {
            var rows = [];
            $('#impulse-chart-entries-list .impulse-chart-entry-row').each(function() {
                rows.push({
                    label: $(this).find('.ch-row-label').val() || '',
                    value: parseFloat($(this).find('.ch-row-value').val()) || 0,
                    color: $(this).find('.ch-row-color').val() || '#9CC3E3'
                });
            });
            $('input[name="chart_entries"]').val(JSON.stringify(rows));
        }

        function syncChartSwatchColors() {
            $('#impulse-chart-entries-list .impulse-chart-entry-row').each(function() {
                var val = $(this).find('.ch-row-color').val() || '#9CC3E3';
                $(this).find('.impulse-color-swatch').css('--swatch-color', val);
            });
        }
        $(document).on('input change', '#impulse-chart-entries-list .ch-row-label, #impulse-chart-entries-list .ch-row-value, #impulse-chart-entries-list .ch-row-color', function() {
            syncChartSwatchColors();
            collectChartEntries();
            autoSaveAndRefresh();
        });

        $(document).on('input', '#impulse-chart-entries-list .ch-row-value', function() {
            var v = this.value || '';
            
            var cleaned = v.replace(/[^0-9.\-]/g, '');
            
            var neg = cleaned.charAt(0) === '-' ? '-' : '';
            cleaned = cleaned.replace(/-/g, '');
            var parts = cleaned.split('.');
            if (parts.length > 1) cleaned = parts[0] + '.' + parts.slice(1).join('');
            cleaned = neg + cleaned;
            if (cleaned !== v) this.value = cleaned;
        });
        $(document).on('click', '#impulse-chart-add-entry', function() {
            var $list = $('#impulse-chart-entries-list');
            if ($list.find('.impulse-chart-entry-row').length >= 8) {
                if (typeof showImpulseToast === 'function') showImpulseToast('Max 8 entries', 'info');
                return;
            }
            var i = $list.find('.impulse-chart-entry-row').length;
            var defaultColor = _chartPalettes.pastel[i % _chartPalettes.pastel.length];
            var rowHtml = '<div class="impulse-chart-entry-row" data-index="' + i + '" style="display:flex;gap:4px;align-items:center">'
                + '<span class="impulse-chart-entry-drag" style="cursor:grab;padding:2px;color:#666;display:inline-flex;align-items:center;flex-shrink:0" title="Drag to reorder"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>'
                + '<input type="text" class="ch-row-label" value="" placeholder="Label" style="flex:1 1 auto;height:26px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';color:' + ImpC.text + ';font-size:11px;padding:0 8px;border-radius:3px;box-sizing:border-box;min-width:0">'
                + '<input type="text" inputmode="decimal" autocomplete="off" class="ch-row-value" value="0" placeholder="0" style="width:44px;flex:0 0 44px;height:26px;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';color:' + ImpC.text + ';font-size:11px;padding:0 6px;border-radius:3px;box-sizing:border-box;text-align:right">'
                + '<div class="impulse-color-setting impulse-color-swatch-only" data-name="chart_entry_color_' + i + '" style="display:block;margin:0;width:26px;height:26px;flex-shrink:0">'
                +   '<div class="impulse-color-row" style="height:26px">'
                +     '<div class="impulse-color-swatch" style="--swatch-color:' + defaultColor + ';width:26px;height:26px;min-width:26px;min-height:26px"></div>'
                +     '<input type="hidden" class="impulse-color-text ch-row-color" value="' + defaultColor + '">'
                +   '</div>'
                + '</div>'
                + '<button type="button" class="impulse-chart-entry-del" title="Remove" style="width:26px;height:26px;padding:0;background:' + ImpC.panel + ';border:1px solid ' + ImpC.border + ';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="' + ImpC.muted + '" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>'
                + '</div>';
            $list.append(rowHtml);
            collectChartEntries();
            autoSaveAndRefresh();
        });
        $(document).on('click', '.impulse-chart-entry-del', function(e) {
            e.stopPropagation();
            $(this).closest('.impulse-chart-entry-row').remove();
            collectChartEntries();
            autoSaveAndRefresh();
        });

        
        $(document).on('change', 'input[type="checkbox"][name="chart_volume"]', function() {
            var _chRebuildType = $('.impulse-panel-right').data('element-type');
            if (_chRebuildType !== 'chart') return;
            setTimeout(function() {
                var _existing = $('.impulse-panel-right').data('existing-settings') || {};
                var _fresh = collectSettingsFromPanel(_existing);
                var _merged = $.extend({}, _existing, _fresh);
                $('.impulse-panel-right').data('existing-settings', _merged);
                $('#impulse-settings-body').html(buildSettingsForm('chart', _merged, []));
                initChartEntriesSortable();
            }, 40);
        });

        
        $(document).on('click', '.impulse-chart-palette-btn', function() {
            var key = $(this).data('palette');
            var palette = _chartPalettes[key];
            if (!palette) return;
            $('#impulse-chart-entries-list .impulse-chart-entry-row').each(function(i) {
                var c = palette[i % palette.length];
                $(this).find('.ch-row-color').val(c);
                $(this).find('.impulse-color-swatch').css('--swatch-color', c);
            });
            collectChartEntries();
            autoSaveAndRefresh();
        });

        

        
        $(document).on('click', '.impulse-btn-group[data-name="hover_highlight_effect"] button:not([disabled])', function() {
            var $group = $(this).closest('.impulse-btn-group');
            setTimeout(function() {
                var anyActive = $group.find('button.active').length > 0;
                var $hhInput = $group.find('input[name="hover_highlight"]');
                if ($hhInput.length) $hhInput.val(anyActive ? '1' : '');

                if (typeof autoSaveAndRefresh === 'function') autoSaveAndRefresh();
            }, 0);
        });

        $(document).on('change', 'select[name="query_type"]', function() {
            if ($(this).val() === 'category') {
                $('.impulse-category-filter').show();
            } else {
                $('.impulse-category-filter').hide();
            }
        });

        function deleteElement(id, fromToolbar) {

            
            if (deletePending[id]) return;

            

            

            
            
            if (id === 'temp-dup' || String(id) === 'temp-dup') {
                if (window.showToast) window.showToast('Duplicate still saving — try again in a moment', 'info');
                return;
            }

            

            viewportPreserve.capture();

            
            if (!fromToolbar && selectedElementId && selectedElementId != id) {
                try {
                    var _iframe = document.getElementById('impulse-iframe');
                    if (_iframe && _iframe.contentDocument) {
                        var targetEl = _iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                        var selectedEl = _iframe.contentDocument.querySelector('.impulse-el[data-id="' + selectedElementId + '"]');
                        if (targetEl && selectedEl && targetEl.contains(selectedEl)) {
                            
                            if (window.impulseDebug) console.log('[delete] Redirecting delete from parent', id, 'to selected child', selectedElementId);
                            id = selectedElementId;
                        }
                    }
                } catch(e) {}
            }

            deletePending[id] = true;

            

            

            

            var _undoSibling = { prev: 0, next: 0 };
            try {
                var _ifrDom = document.getElementById('impulse-iframe');
                if (_ifrDom && _ifrDom.contentDocument) {
                    var _delEl = _ifrDom.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (_delEl && _delEl.parentElement) {
                        var _sibs = Array.from(_delEl.parentElement.children).filter(function (n) {
                            return n.classList && n.classList.contains('impulse-el') && n.dataset && n.dataset.id;
                        });
                        var _myIdx = _sibs.indexOf(_delEl);
                        if (_myIdx > 0) _undoSibling.prev = parseInt(_sibs[_myIdx - 1].dataset.id) || 0;
                        if (_myIdx >= 0 && _myIdx < _sibs.length - 1) _undoSibling.next = parseInt(_sibs[_myIdx + 1].dataset.id) || 0;
                    }
                }
            } catch (_e) {}

            

            var _allDeleteIds = [id];
            try {
                var _iframe = document.getElementById('impulse-iframe');
                if (_iframe && _iframe.contentDocument) {
                    var _root = _iframe.contentDocument.querySelector('.impulse-el[data-id="' + id + '"]');
                    if (_root) {
                        _root.querySelectorAll('.impulse-el[data-id]').forEach(function(c) {
                            var cid = parseInt(c.getAttribute('data-id'), 10);
                            if (cid && cid !== id) { _allDeleteIds.push(cid); deletePending[cid] = true; }
                        });
                    }
                }
            } catch(e) {}

            clearTimeout(autoSaveTimer);
            clearTimeout(autoRefreshTimer);
            clearTimeout(animSaveTimer);
            
            for (var _qi = saveQueue.length - 1; _qi >= 0; _qi--) {
                if (_allDeleteIds.indexOf(saveQueue[_qi].id) !== -1) saveQueue.splice(_qi, 1);
            }

            if ($('.impulse-panel-right').data('element-id') == id) {
                $('.impulse-panel-right').removeData('element-id');
                $('.impulse-panel-right').removeData('existing-settings');
            }

            if (cellGridSettingsCache[id]) {
                delete cellGridSettingsCache[id];
            }

            if (selectedElementId == id) {
                selectedElementId = null;
                selectedElementType = null;
                showPageSettings();
            }

            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-hide-element', id: id }, '*');
            }

            var $structItem = $('.impulse-structure-item[data-id="' + id + '"]');
            if ($structItem.length) {
                $structItem.css({
                    transition: 'transform 0.25s cubic-bezier(0.4,0,0.2,1), opacity 0.25s cubic-bezier(0.4,0,0.2,1), height 0.2s cubic-bezier(0.4,0,0.2,1) 0.1s, margin 0.2s cubic-bezier(0.4,0,0.2,1) 0.1s, padding 0.2s cubic-bezier(0.4,0,0.2,1) 0.1s',
                    overflow: 'hidden',
                    height: $structItem.outerHeight() + 'px'
                });
                requestAnimationFrame(function() {
                    $structItem.css({ opacity: 0, transform: 'scale(0.85) translateX(-8px)' });
                    setTimeout(function() {
                        $structItem.css({ height: 0, margin: 0, padding: 0 });
                    }, 100);
                    setTimeout(function() { $structItem.remove(); }, 400);
                });
            }

            
            function _proceedWithDelete() {
                var _pageId = Impulse.pageId || 0;
                
                $.ajax({
                    url: Impulse.api + 'elements/' + id + '/tree' + (_pageId ? '?page_id=' + _pageId : ''),
                    method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    success: function(treeData) {
                        
                        $.ajax({
                            url: Impulse.api + 'elements/' + id + (_pageId ? '?page_id=' + _pageId : ''),
                            method: 'DELETE',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            success: function() {
                                _allDeleteIds.forEach(function(did){ delete deletePending[did]; });
                                saveToHistory('delete', {
                                    elementId: id,
                                    elementType: treeData.type || treeData.section_type,
                                    settings: treeData.settings,
                                    parentId: treeData.parent_id || 0,
                                    sortOrder: treeData.sort_order || 0,

                                    
                                    
                                    prevSiblingId: _undoSibling.prev || 0,
                                    nextSiblingId: _undoSibling.next || 0,
                                    subtree: treeData  
                                });

                                

                                

                                
                                if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) { updateStructureTree(); }
                            },
                            error: function(xhr) {
                                _allDeleteIds.forEach(function(did){ delete deletePending[did]; });

                                
                                
                                if (xhr && xhr.status === 404) {
                                    _allDeleteIds.forEach(_pruneOrphanFromDom);
                                    if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) { updateStructureTree(); }
                                    return;
                                }

                                
                                
                                refreshPreview();
                            }
                        });
                    },
                    error: function(xhr) {
                        
                        $.ajax({
                            url: Impulse.api + 'elements/' + id + (_pageId ? '?page_id=' + _pageId : ''),
                            method: 'DELETE',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            success: function() {
                                _allDeleteIds.forEach(function(did){ delete deletePending[did]; });
                                
                                if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) { updateStructureTree(); }
                            },
                            error: function(xhr) {
                                _allDeleteIds.forEach(function(did){ delete deletePending[did]; });

                                
                                if (xhr && xhr.status === 404) {
                                    _allDeleteIds.forEach(_pruneOrphanFromDom);
                                    if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) { updateStructureTree(); }
                                    return;
                                }
                                refreshPreview();
                            }
                        });
                    }
                });
            }

            
            function _pruneOrphanFromDom(elId) {
                try {
                    var iframe = document.getElementById('impulse-iframe');
                    if (iframe && iframe.contentDocument) {
                        var node = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elId + '"]');
                        if (node && node.parentNode) {
                            node.parentNode.removeChild(node);
                        }
                    }
                    
                    $('.impulse-structure-item[data-id="' + elId + '"]').remove();
                    if (typeof selectedElementId !== 'undefined' && String(selectedElementId) === String(elId)) {
                        selectedElementId = null;
                        if (typeof deselectElement === 'function') { try { deselectElement(); } catch(_) {} }
                    }
                } catch (_) {}
            }

            

            if (saveInFlight || saveQueue.length > 0) {
                var _deleteWait = setInterval(function() {
                    if (!saveInFlight && saveQueue.length === 0) {
                        clearInterval(_deleteWait);
                        _proceedWithDelete();
                    }
                }, 50);
            } else {
                _proceedWithDelete();
            }
        }

        function duplicateSlide(sliderId, slideIndex) {
            if (!sliderId) return;
            $.ajax({
                url: Impulse.api + 'elements/' + sliderId + '/duplicate-slide',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ page_id: Impulse.pageId || 0, slide_index: slideIndex }),
                success: function(resp) {
                    if (!resp || !resp.success) { window.showToast('Duplicate failed'); return; }
                    window.showToast('Slide duplicated');
                    
                    refreshElement(sliderId);
                    setTimeout(function() {
                        var iframe = document.getElementById('impulse-iframe');
                        if (iframe && iframe.contentWindow) {
                            iframe.contentWindow.postMessage({
                                type: 'impulse-go-to-slide',
                                sliderId: sliderId,
                                slideIndex: resp.new_slide_index
                            }, '*');
                        }
                        updateStructureTree();
                    }, 600);
                },
                error: function() { window.showToast('Duplicate failed'); }
            });
        }
        function duplicateElement(id, onDone) {
            var pageId = Impulse.pageId || 0;
            var iframe = document.getElementById('impulse-iframe');

            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-clone-element', id: id }, '*');
            }

            $.ajax({
                url: Impulse.api + 'elements/' + id + '/duplicate',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ page_id: pageId }),
                success: function(resp) {
                    if (resp && resp.id) {
                        saveToHistory('add', {
                            elementId: resp.id,
                            elementType: resp.type || resp.section_type,
                            parentId: resp.parent_id || 0,
                            sortOrder: resp.sort_order || 0,
                            settings: resp.settings || {}
                        });
                        
                        if (iframe && iframe.contentWindow && resp.id_map) {
                            iframe.contentWindow.postMessage({
                                type: 'impulse-remap-ids',
                                old_id: id,
                                id_map: resp.id_map
                            }, '*');
                        }
                        if (typeof onDone === 'function') onDone(resp.id);
                        
                    }
                },
                error: function(xhr) {
                    
                    if (iframe && iframe.contentDocument) {
                        var tempEl = iframe.contentDocument.querySelector('.impulse-el[data-id="temp-dup"]');
                        if (tempEl) tempEl.remove();
                    }
                    window.showToast('Duplicate failed: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.status), 'error');
                }
            });
        }

        function reorderElement(sourceId, targetId, position, fullRefresh, onDone) {

            

            

            

            function _afterReorder() {
                if (fullRefresh) {
                    refreshPreview();
                    setTimeout(function() {
                        if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) updateStructureTree();
                    }, 450);
                } else if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) {
                    updateStructureTree();
                }
            }

            

            

            

            

            
            var _reorderPageId = (window.Impulse && Impulse.pageId) ? Impulse.pageId : 0;
            $.ajax({
                url: Impulse.api + 'elements/' + sourceId + (_reorderPageId ? '?page_id=' + _reorderPageId : ''),
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                async: false,
                success: function(elementData) {
                    var oldParentId = elementData.parent_id || 0;
                    var oldSortOrder = elementData.sort_order || 0;
                    var oldCellRow = (elementData.settings && elementData.settings._cell_row !== undefined) ? elementData.settings._cell_row : null;
                    var oldCellCol = (elementData.settings && elementData.settings._cell_col !== undefined) ? elementData.settings._cell_col : null;

                    $.ajax({
                        url: Impulse.api + 'elements/' + sourceId + '/reorder',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ target_id: targetId, position: position, page_id: _reorderPageId }),
                        success: function(resp) {
                            saveToHistory('reorder', {
                                sourceId: sourceId,
                                targetId: targetId,
                                position: position,
                                oldParentId: oldParentId,
                                oldSortOrder: oldSortOrder,
                                oldCellRow: oldCellRow,
                                oldCellCol: oldCellCol
                            });
                            _afterReorder();

                            
                            
                            if (typeof onDone === 'function') onDone();
                        },
                        error: function(xhr, status, error) {
                            console.error('reorderElement failed:', error, xhr.responseText);
                        }
                    });
                },
                error: function() {
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + sourceId + '/reorder',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ target_id: targetId, position: position, page_id: _reorderPageId }),
                        success: function(resp) {
                            _afterReorder();
                            if (typeof onDone === 'function') onDone();
                        },
                        error: function(xhr, status, error) {
                            console.error('reorderElement failed:', error, xhr.responseText);
                        }
                    });
                }
            });
        }

        function moveElementInto(sourceId, containerId, gridCellIndex, cellRow, cellCol, slideIndex, fullRefresh) {
            
            if (String(sourceId) === String(containerId)) return;

            

            
            
            function _afterMove() {
                if (fullRefresh) {
                    refreshPreview();
                    setTimeout(function() {
                        if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) updateStructureTree();
                    }, 450);
                } else {
                    refreshElement(sourceId);
                    if ($('.impulse-panel-tab[data-tab="structure"]').hasClass('active')) { updateStructureTree(); }
                }
            }

            var requestData = { parent_id: containerId, page_id: Impulse.pageId || 0 };
            if (gridCellIndex !== null && gridCellIndex !== undefined) {
                requestData.grid_cell_index = gridCellIndex;
            }
            if (cellRow !== null && cellRow !== undefined) {
                requestData.cell_row = cellRow;
            }
            if (cellCol !== null && cellCol !== undefined) {
                requestData.cell_col = cellCol;
            }
            if (slideIndex !== null && slideIndex !== undefined) {
                requestData.slide_index = parseInt(slideIndex) || 0;
            }

            $.ajax({
                url: Impulse.api + 'elements/' + sourceId,
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                async: false,
                success: function(elementData) {
                    var oldParentId = elementData.parent_id || 0;
                    var oldSortOrder = elementData.sort_order || 0;
                    var oldCellRow = (elementData.settings && elementData.settings._cell_row !== undefined) ? elementData.settings._cell_row : null;
                    var oldCellCol = (elementData.settings && elementData.settings._cell_col !== undefined) ? elementData.settings._cell_col : null;

                    $.ajax({
                        url: Impulse.api + 'elements/' + sourceId + '/move-into',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        success: function(resp) {
                            saveToHistory('move', {
                                sourceId: sourceId,
                                targetId: containerId,
                                oldParentId: oldParentId,
                                oldSortOrder: oldSortOrder,
                                oldCellRow: oldCellRow,
                                oldCellCol: oldCellCol,
                                
                                gridCellIndex: gridCellIndex,
                                cellRow: cellRow,
                                cellCol: cellCol,
                                slideIndex: slideIndex
                            });

                            

                            _afterMove();
                        },
                        error: function(xhr, status, error) {
                            console.error('moveElementInto failed:', error, xhr.responseText);
                        }
                    });
                },
                error: function() {
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + sourceId + '/move-into',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        success: function(resp) {
                            _afterMove();
                        },
                        error: function(xhr, status, error) {
                            console.error('moveElementInto failed:', error, xhr.responseText);
                        }
                    });
                }
            });
        }

        

        var styleClipboard = null; 
        try { var _sc = sessionStorage.getItem('impulse_style_clipboard'); if (_sc) styleClipboard = JSON.parse(_sc); } catch(e) {}

        var CLIPBOARD_KEY = 'impulse_clipboard';
        var TEMPLATES_KEY = 'impulse_user_templates';

        function getClipboard() {
            try {
                var data = localStorage.getItem(CLIPBOARD_KEY);
                return data ? JSON.parse(data) : null;
            } catch(e) {
                return null;
            }
        }

        function setClipboard(data) {
            try {
                localStorage.setItem(CLIPBOARD_KEY, JSON.stringify(data));
            } catch(e) {
                console.error('Failed to save to clipboard:', e);
            }
        }

        

        

        
        var _templateCache         = null;  
        var _platformSectionsCache = null;  

        
        
        function flatTreeToNested(arr) {
            if (!Array.isArray(arr) || !arr.length) return null;
            var byParent = {};
            arr.forEach(function(el) {
                var pid = (el.parent_id === null || el.parent_id === undefined) ? '_root' : el.parent_id;
                (byParent[pid] = byParent[pid] || []).push(el);
            });
            
            Object.keys(byParent).forEach(function(k) {
                byParent[k].sort(function(a, b) { return (a.sort_order || 0) - (b.sort_order || 0); });
            });
            var roots = byParent._root || [];
            if (!roots.length) return null;
            function build(node) {
                var kids = byParent[node.id] || [];
                return {
                    type:     node.type     || 'section',
                    settings: node.settings || {},
                    children: kids.map(build)
                };
            }

            
            if (roots.length === 1) return build(roots[0]);
            return {
                type: 'section',
                settings: {},
                children: roots.map(build)
            };
        }

        function flattenItem(item, source) {
            var raw = item.element_tree;
            
            var nested = Array.isArray(raw) ? flatTreeToNested(raw)
                       : (raw && typeof raw === 'object' ? raw : null);
            if (!nested) nested = { type: 'section', settings: {}, children: [] };
            return {
                id:           item.id,
                name:         item.name,
                type:         nested.type     || 'section',
                settings:     nested.settings || {},
                children:     nested.children || [],
                html_preview: item.html_preview || '',
                tier:         (item.tier === 'free') ? 'free' : 'pro',
                source:       source || 'local'
            };
        }
        function loadUserTemplates(callback) {
            var done = 0;
            var finish = function() {
                if (++done < 2) return;
                if (callback) callback(_templateCache || []);
            };
            $.ajax({
                url: Impulse.api + 'library/sections',
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(r) {
                var items = (r && r.items) ? r.items : [];
                _templateCache = items.map(function(i) { return flattenItem(i, 'local'); });
            }).fail(function() {
                _templateCache = _templateCache || [];
            }).always(finish);
            $.ajax({
                url: Impulse.api + 'library/platform/sections',
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(r) {
                var items = (r && r.items) ? r.items : [];
                _platformSectionsCache = items.map(function(i) { return flattenItem(i, 'platform'); });
            }).fail(function() {
                _platformSectionsCache = _platformSectionsCache || [];
            }).always(finish);
        }
        function getUserTemplates() { return _templateCache || []; }
        function getPlatformSections() { return _platformSectionsCache || []; }
        
        $(document).on('keydown', function(e) {
            
            var isContentEditable = $(e.target).is('[contenteditable="true"]');
            var isTextInput = $(e.target).is('input, textarea, select') && !$(e.target).is('input[type="checkbox"], input[type="radio"], input[type="button"], input[type="submit"], input[type="reset"], input[type="range"], input[type="color"], input[type="file"]');

            if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
                
                if (!isContentEditable && !isTextInput) {
                    e.preventDefault();
                    $('#impulse-undo').click();
                }
            }

            if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.shiftKey && e.key === 'z'))) {
                if (!isContentEditable && !isTextInput) {
                    e.preventDefault();
                    $('#impulse-redo').click();
                }
            }

            
            
            if ((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'C')) {
                if (!isContentEditable && !isTextInput) {
                    e.preventDefault();
                    if (e.shiftKey) copyStyle();
                    else            copyElement();
                }
            }

            
            if ((e.ctrlKey || e.metaKey) && (e.key === 'v' || e.key === 'V')) {

                
                if (e.shiftKey) {
                    if (!isContentEditable && !isTextInput) {
                        e.preventDefault();
                        pasteStyle();
                    }
                    return;
                }
                var $openPicker = $('.impulse-color-picker.open');
                if ($openPicker.length) {
                    var $hex = $openPicker.find('.impulse-picker-hex input');
                    if (!$hex.is(':focus')) {
                        $hex.focus().select();
                        
                    }
                    return;
                }
                if (!isContentEditable && !isTextInput) {
                    e.preventDefault();
                    pasteElement();
                }
            }

            if ((e.ctrlKey || e.metaKey) && e.key === 'd') {
                e.preventDefault();
                if (selectedElementId) {
                    duplicateElement(selectedElementId);
                }
            }

            if ((e.key === 'Delete' || e.key === 'Backspace') && selectedElementId) {
                var activeEl = document.activeElement;
                var tagName = activeEl ? activeEl.tagName.toLowerCase() : '';
                var isEditable = activeEl && (activeEl.isContentEditable || activeEl.contentEditable === 'true');
                var isInput = tagName === 'input' || tagName === 'textarea' || tagName === 'select' || isEditable;

                if (isInput) {
                    return;
                }
                
                e.preventDefault();
                deleteElement(selectedElementId);
            }

            if (e.key === 'Escape') {
                e.preventDefault();
                deselectElement();
            }
        });

        
        
        function copyElement() {
            if (!selectedElementId) {
                window.showToast('Select an element to copy');
                return;
            }
            $.ajax({
                url: Impulse.api + 'elements/' + selectedElementId + '/tree',
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                success: function(tree) {
                    if (!tree || !tree.type) { window.showToast('Failed to copy element'); return; }
                    setClipboard({ type: tree.type, tree: tree, timestamp: Date.now() });
                    var n = countTreeNodes(tree);
                    window.showToast(n > 1 ? ('Copied — ' + n + ' elements') : 'Element copied');
                },
                error: function() {
                    window.showToast('Failed to copy element');
                }
            });
        }
        function countTreeNodes(node) {
            var n = 1;
            if (node && node.children) { for (var i = 0; i < node.children.length; i++) n += countTreeNodes(node.children[i]); }
            return n;
        }

        function pasteElement() {
            var clipboard = getClipboard();

            var tree = clipboard && (clipboard.tree || (clipboard.settings ? { type: clipboard.type, settings: clipboard.settings } : null));
            if (!tree) {
                window.showToast('Clipboard is empty');
                return;
            }
            if (!selectedElementId) {
                window.showToast('Select a target element');
                return;
            }

            
            var _pasteContainers = ['section','rows','columns','slider','modal'];
            var parentId = null, afterId = 0;

            if (_pasteContainers.indexOf(selectedElementType) !== -1) {
                parentId = selectedElementId;
            } else {
                afterId = selectedElementId;
                $.ajax({
                    url: Impulse.api + 'elements/' + selectedElementId,
                    method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    async: false,
                    success: function(data) { parentId = data.parent_id || null; }
                });
            }

            if (!parentId || parentId === 0) {
                window.showToast('Cannot paste at root level');
                return;
            }

            $.ajax({
                url: Impulse.api + 'elements/paste-tree',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({
                    page_id:   Impulse.pageId,
                    parent_id: parentId,
                    after_id:  afterId,
                    tree:      tree
                }),
                success: function(resp) {
                    window.showToast('Pasted');
                    refreshPreview();
                    setTimeout(updateStructureTree, 300);
                },
                error: function(xhr) {
                    var msg = (xhr.responseJSON && xhr.responseJSON.error) ? xhr.responseJSON.error : 'Failed to paste';
                    window.showToast(msg, 'error');
                }
            });
        }

        function saveAsTemplate() {
            if (!selectedElementId) {
                window.showToast('Select an element to save as template');
                return;
            }
            saveAsTemplateById(selectedElementId);
        }

        

        function saveAsTemplateById(elementId) {
            if (!elementId) {
                window.showToast('No element to save');
                return;
            }

            var $modal = $('#impulse-template-name-modal');
            var $input = $('#impulse-template-name-input');
            $input.val('');
            $modal.show();
            setTimeout(function() { $input.focus(); }, 100);

            var handleSave = function() {
                var templateName = $input.val().trim();
                if (!templateName) {
                    $input.css('border-color', ''+ImpC.dim+'');
                    return;
                }
                $modal.hide();

                

                var htmlPreview = '';
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentDocument) {
                    var node = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elementId + '"]');
                    if (node) {
                        var clone = node.cloneNode(true);
                        var editorClasses = ['selected','is-hover','is-editing','is-drop-target',
                                             'dragging','toolbar-faded','is-empty-select'];
                        var editorAttrs   = ['contenteditable','draggable','spellcheck',
                                             'data-drag-handle','data-hover-id'];
                        var scrub = function(el) {
                            if (!el || el.nodeType !== 1) return;
                            editorClasses.forEach(function(c) { el.classList.remove(c); });
                            editorAttrs.forEach(function(a) { el.removeAttribute(a); });
                            for (var i = 0; i < el.children.length; i++) scrub(el.children[i]);
                        };
                        scrub(clone);
                        htmlPreview = clone.outerHTML;
                    }
                }

                $.ajax({
                    url: Impulse.api + 'elements/' + elementId + '/tree',
                    method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce }
                }).done(function(tree) {
                    $.ajax({
                        url: Impulse.api + 'library/sections',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({
                            name:         templateName,
                            element_tree: tree,
                            html_preview: htmlPreview
                        })
                    }).done(function(r) {
                        if (r && r.success) {
                            loadUserTemplates(function() { renderUserTemplates(); });
                            window.showToast('Template saved');
                        } else {
                            window.showToast((r && r.error) || 'Failed to save template');
                        }
                    }).fail(function(xhr) {
                        var msg = (xhr && xhr.responseJSON && xhr.responseJSON.error) || 'Failed to save template';
                        window.showToast(msg);
                    });
                }).fail(function() {
                    window.showToast('Failed to read element');
                });
            };

            $('#impulse-template-name-save').off('click').on('click', handleSave);
            $input.off('keydown').on('keydown', function(e) {
                $(this).css('border-color', ''+ImpC.border+'');
                if (e.key === 'Enter') handleSave();
            });
            $modal.find('.impulse-modal-close').off('click').on('click', function() {
                $modal.hide();
            });
        }

        var _sectionsTagFilter = null;

        function collectTags(items) {
            var set = {};
            items.forEach(function(it) {
                var tags = it && it.tags;
                if (!Array.isArray(tags)) tags = (tags ? String(tags).split(',') : []);
                tags.forEach(function(t) {
                    t = String(t || '').trim();
                    if (t) set[t.toLowerCase()] = t;
                });
            });
            return Object.keys(set).sort().map(function(k) { return set[k]; });
        }

        function renderTagFilterBar(tags, activeTag, surfaceId) {
            if (!tags.length) return '';
            var html = '<div class="impulse-tag-filter" data-surface="' + surfaceId + '">';
            html += '<button type="button" class="impulse-tag-pill' + (activeTag ? '' : ' is-active') + '" data-tag="">All</button>';
            tags.forEach(function(t) {
                var isActive = activeTag && activeTag.toLowerCase() === t.toLowerCase();
                html += '<button type="button" class="impulse-tag-pill' + (isActive ? ' is-active' : '') + '" data-tag="' + escapeHtml(t) + '">' + escapeHtml(t) + '</button>';
            });
            html += '</div>';
            return html;
        }

        function filterByTag(items, tag) {
            if (!tag) return items;
            var lc = tag.toLowerCase();
            return items.filter(function(it) {
                var tags = it && it.tags;
                if (!Array.isArray(tags)) tags = (tags ? String(tags).split(',') : []);
                return tags.some(function(t) { return String(t || '').trim().toLowerCase() === lc; });
            });
        }

        

        

        

        function renderUserTemplates() {
            var $container = $('#impulse-my-templates');
            var localItems    = getUserTemplates();
            var platformItems = getPlatformSections();

            if (!localItems.length && !platformItems.length) {
                $container.html('<div class="impulse-my-templates-empty">No templates yet.</div>');
                return;
            }

            var platformTags     = collectTags(platformItems);
            var platformFiltered = filterByTag(platformItems, _sectionsTagFilter);
            var canUpload        = !!(window.Impulse && Impulse.canUploadToPlatform);
            var html = '';

            var tileHtml = function(tpl) {
                var isPlatform = tpl.source === 'platform';
                var nameAttr = ' title="' + escapeHtml(tpl.name) + '"';

                var locked   = isPlatform && tpl.tier === 'pro' && window.isProLocked && window.isProLocked();
                var lockCls  = locked ? ' impulse-pro-locked' : '';
                var itemHtml = '<div class="impulse-my-template-item' + lockCls + '" data-template-id="' + tpl.id + '" data-source="' + (isPlatform ? 'platform' : 'local') + '"' + (locked ? ' data-pro-label="' + escapeHtml(tpl.name) + ' template"' : '') + ' draggable="true"' + nameAttr + '>';
                if (tpl.html_preview) {
                    itemHtml += '<div class="template-preview template-preview-html" data-template-id="' + tpl.id + '" data-source="' + (isPlatform ? 'platform' : 'local') + '"></div>';
                } else {
                    itemHtml += '<div class="template-preview">' + generateTemplateWireframe(tpl) + '</div>';
                }
                if (!isPlatform) {

                    itemHtml += '<button type="button" class="template-delete" data-id="' + tpl.id + '" title="Delete"><svg viewBox="0 0 24 24" width="10" height="10" stroke="currentColor" fill="none" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
                    if (canUpload) {
                        itemHtml += '<button type="button" class="template-upload" data-id="' + tpl.id + '" data-kind="section" title="Upload to Platform Library"><svg viewBox="0 0 24 24" width="10" height="10" stroke="currentColor" fill="none" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg></button>';
                    }
                }

                itemHtml += '<div class="template-name">' + escapeHtml(tpl.name) + '</div>';
                itemHtml += '</div>';
                return itemHtml;
            };

            if (platformItems.length) {
                html += '<div class="impulse-lib-group-header">LIBRARY</div>';
                html += renderTagFilterBar(platformTags, _sectionsTagFilter, 'sections');
                html += '<div class="impulse-my-templates-group">';
                platformFiltered.forEach(function(t) { html += tileHtml(t); });
                html += '</div>';
            }
            if (localItems.length) {
                html += '<div class="impulse-lib-group-header">MY SECTIONS</div>';
                html += '<div class="impulse-my-templates-group">';
                localItems.forEach(function(t) { html += tileHtml(t); });
                html += '</div>';
            }
            $container.html(html);

            
            
            var mountAll = function(items) {
                items.forEach(function(tpl) {
                    if (!tpl.html_preview) return;
                    var sel = '.template-preview-html[data-template-id="' + tpl.id + '"][data-source="' + (tpl.source === 'platform' ? 'platform' : 'local') + '"]';
                    var $slot = $container.find(sel);
                    if (!$slot.length) return;
                    mountLibraryPreviewIframe($slot[0], tpl.html_preview);
                });
            };
            mountAll(platformFiltered);
            mountAll(localItems);
        }

        $(document).on('click', '.impulse-tag-filter[data-surface="sections"] .impulse-tag-pill', function() {
            var tag = $(this).data('tag') || '';
            
            if (tag && _sectionsTagFilter && tag.toLowerCase() === _sectionsTagFilter.toLowerCase()) tag = '';
            _sectionsTagFilter = tag || null;
            renderUserTemplates();
        });

        

        
        function stripEditorChromeMarkup(markup) {
            if (!markup || typeof DOMParser === 'undefined') return markup || '';
            try {
                var doc = new DOMParser().parseFromString(markup, 'text/html');
                doc.querySelectorAll(
                    '.impulse-el-toolbar,.impulse-el-handle,.impulse-toolbox,.impulse-toolbox-btn,'
                    + '.impulse-block-nav,.impulse-section-bracket,'
                    + '.impulse-cell-empty-indicator,.impulse-grid-empty-indicator,'
                    + '.impulse-dropzone,.impulse-tab-dropzone,.impulse-toggle-dropzone,'
                    + '.impulse-new-slider-dropzone,.impulse-root-dropzone,'
                    + '.impulse-add-screen-btn,.impulse-add-section-btn,'
                    + '[class*="impulse-resize-"],[class*="impulse-grid-cell-toolbar"],[class*="impulse-cell-handle"]'
                ).forEach(function(el) { el.remove(); });
                return doc.body.innerHTML;
            } catch (e) { return markup; }
        }

        

        
        function mountLibraryPreviewIframe(slotEl, markup, opts) {
            opts = opts || {};
            markup = stripEditorChromeMarkup(markup);

            

            

            if (!opts.animated && markup) {
                markup = markup.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '');
            }
            if (!slotEl.style.cssText) {

                

                slotEl.style.cssText = 'position:relative;width:100%;overflow:hidden;border-radius:3px;background:transparent';
            }

            var pluginUrl = (window.Impulse && Impulse.pluginUrl) ? Impulse.pluginUrl.replace(/\/$/, '') : '';
            var ver       = (window.Impulse && Impulse.version)   ? Impulse.version : Date.now();
            var cssHref   = pluginUrl + '/assets/css/frontend.css?v=' + ver;

            

            

            

            var scripts = '';
            if (opts.animated) {
                scripts =
                    '<script src="' + pluginUrl + '/assets/js/vendor/three.min.js?v=' + ver + '"></script>' +
                    '<script src="' + pluginUrl + '/assets/js/impulse-3d-text.js?v=' + ver + '"></script>' +
                    [
                        '/assets/js/impulse-animations.js',
                        '/assets/js/impulse-wave.js',
                        '/assets/js/impulse-fx-engine.js',
                        '/assets/js/impulse-3d-effects.js',
                        '/assets/js/impulse-section-fx.js'
                    ].map(function(p) { return '<script src="' + pluginUrl + p + '?v=' + ver + '" defer></script>'; }).join('');
            }

            var shell =
                '<!DOCTYPE html><html><head><meta charset="utf-8">' +
                '<link rel="stylesheet" href="' + cssHref + '">' +
                '<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden;width:1440px}' +
                'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}' +
                
                '.impulse-el-toolbar,.impulse-el-drag,.impulse-el-duplicate,.impulse-el-delete,' +
                '.impulse-cell-empty-indicator,.impulse-grid-empty-indicator,' +
                '.impulse-dropzone,.impulse-tab-dropzone,.impulse-toggle-dropzone,' +
                '.impulse-new-slider-dropzone,.impulse-root-dropzone,' +
                '.impulse-add-screen-btn,.impulse-add-section-btn{display:none!important}' +
                
                '.impulse-el{outline:none!important;border-color:transparent!important}' +
                '.impulse-el.selected,.impulse-el:hover{outline:none!important}' +
                
                '.impulse-display-text h1,.impulse-display-text h2,.impulse-display-text h3,' +
                '.impulse-display-text [data-impulse-3d-text]{opacity:1!important}' +
                'canvas[data-impulse-3d-text-canvas]{display:none!important}' +
                
                (opts.animated ? '' :
                    '*,*::before,*::after{animation:none!important;transition:none!important}' +
                    '.impulse-animated,[data-animated]{opacity:1!important;transform:none!important;visibility:visible!important}' +
                    '.impulse-la-asset{opacity:1!important}' +
                    'canvas.impulse-la-canvas,canvas.impulse-la-3d-canvas{display:none!important}'
                ) +
                '</style></head><body>' + markup + scripts + '</body></html>';

            

            
            var slotWidth   = slotEl.clientWidth || opts.fallbackWidth || 120;
            var naturalW    = 1440;
            var initialH    = opts.aspect ? Math.round(naturalW / opts.aspect) : Math.round(naturalW * 9 / 16);
            var scale       = slotWidth / naturalW;

            var iframe = document.createElement('iframe');
            iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts');
            iframe.style.cssText =
                'width:' + naturalW + 'px;height:' + initialH + 'px;border:0;' +
                'transform:scale(' + scale + ');transform-origin:top left;' +
                'pointer-events:none;' +
                'position:absolute;top:0;left:0';
            iframe.srcdoc = shell;

            

            slotEl.style.height = '0px';

            

            iframe.addEventListener('load', function() {
                try {
                    var doc = iframe.contentDocument;
                    if (!doc) return;
                    
                    requestAnimationFrame(function() {
                        var measured = Math.max(
                            doc.body.scrollHeight || 0,
                            doc.documentElement.scrollHeight || 0
                        );

                        if (measured < 40) measured = 80;
                        if (opts.maxScaledHeight) {

                            var maxNatural = Math.round(opts.maxScaledHeight / scale);
                            if (measured > maxNatural) measured = maxNatural;
                        } else {

                            var maxH = Math.round(naturalW * 9 / 16);
                            if (measured > maxH) measured = maxH;
                        }
                        iframe.style.height = measured + 'px';
                        slotEl.style.height = (measured * scale) + 'px';
                    });
                } catch (_e) {}
            });

            slotEl.innerHTML = '';
            slotEl.appendChild(iframe);
        }

        function generateTemplateWireframe(tpl) {
            var children = tpl.children || [];
            var elements = [];

            function collectTypes(node, depth) {
                if (depth > 2) return;
                var t = node.type || tpl.type;
                elements.push(t);
                if (node.children) {
                    node.children.forEach(function(c) { collectTypes(c, depth + 1); });
                }
            }
            
            if (children.length > 0) {
                children.forEach(function(c) { collectTypes(c, 0); });
            } else {
                elements.push(tpl.type);
            }

            var svgParts = [];
            var y = 6;
            var maxItems = Math.min(elements.length, 6);
            var h = Math.max(8, Math.floor(54 / maxItems));
            
            for (var i = 0; i < maxItems; i++) {
                var type = elements[i];
                var fill = '#ccc';
                var rh = h - 2;
                
                if (type === 'title' || type === 'h1' || type === 'h2') {
                    svgParts.push('<rect x="10" y="' + y + '" width="60" height="' + Math.min(rh, 6) + '" rx="1" fill="'+ImpC.muted+'"/>');
                } else if (type === 'text') {
                    svgParts.push('<rect x="10" y="' + y + '" width="80" height="' + Math.min(rh, 4) + '" rx="1" fill="#ccc"/>');
                    if (rh > 5) svgParts.push('<rect x="10" y="' + (y + Math.min(rh, 4) + 2) + '" width="65" height="3" rx="1" fill="#ddd"/>');
                } else if (type === 'button') {
                    svgParts.push('<rect x="10" y="' + y + '" width="36" height="' + Math.min(rh, 10) + '" rx="3" fill="#666"/>');
                } else if (type === 'image') {
                    svgParts.push('<rect x="10" y="' + y + '" width="80" height="' + Math.min(rh, 16) + '" rx="2" fill="'+ImpC.text+'"/>');
                } else if (type === 'grid' || type === 'rows') {
                    svgParts.push('<rect x="10" y="' + y + '" width="36" height="' + Math.min(rh, 10) + '" rx="2" fill="'+ImpC.text+'"/>');
                    svgParts.push('<rect x="52" y="' + y + '" width="36" height="' + Math.min(rh, 10) + '" rx="2" fill="'+ImpC.text+'"/>');
                } else if (type === 'icon_card') {
                    svgParts.push('<circle cx="18" cy="' + (y + rh/2) + '" r="' + Math.min(rh/2, 5) + '" fill="#ccc"/>');
                } else if (type === 'section') {
                    svgParts.push('<rect x="4" y="' + y + '" width="92" height="' + Math.min(rh, 14) + '" rx="2" fill="#f0f0f0" stroke="#ddd" stroke-width="0.5"/>');
                } else {
                    svgParts.push('<rect x="10" y="' + y + '" width="80" height="' + Math.min(rh, 8) + '" rx="1" fill="'+ImpC.text+'"/>');
                }
                y += h;
            }
            
            if (elements.length > maxItems) {
                svgParts.push('<text x="50" y="' + (y + 4) + '" text-anchor="middle" fill="'+ImpC.muted+'" font-size="6">+' + (elements.length - maxItems) + ' more</text>');
            }
            
            var totalH = Math.max(y + 4, 40);
            return '<svg viewBox="0 0 100 ' + totalH + '" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:100%;height:auto;display:block">' +
                '<rect width="100" height="' + totalH + '" rx="3" fill="'+ImpC.light+'"/>' +
                svgParts.join('') + '</svg>';
        }

        
        
        $(document).on('click', '.impulse-my-template-item .template-upload', function(e) {
            e.stopPropagation();
            var sourceId = $(this).data('id');
            if (!sourceId) return;
            $.ajax({
                url: Impulse.api + 'library/platform/upload',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ kind: 'section', source_id: sourceId })
            }).done(function(r) {
                if (r && r.success) {
                    window.showToast && window.showToast('Uploaded to Platform Library');
                    loadUserTemplates(function() { renderUserTemplates(); });
                } else {
                    window.showToast && window.showToast((r && r.error) || 'Upload failed');
                }
            }).fail(function(xhr) {
                var msg = (xhr && xhr.responseJSON && xhr.responseJSON.error) || 'Upload failed';
                window.showToast && window.showToast(msg);
            });
        });

        $(document).on('click', '.impulse-my-template-item .template-delete', function(e) {
            e.stopPropagation();
            var id = $(this).data('id');

            _templateCache = (_templateCache || []).filter(function(t) { return t.id !== id; });
            renderUserTemplates();

            
            if (hoverTimeout) { clearTimeout(hoverTimeout); hoverTimeout = null; }
            $hoverPreview.hide().find('.preview-content').empty();

            $.ajax({
                url: Impulse.api + 'library/sections/' + id,
                method: 'DELETE',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(r) {
                if (r && r.success) window.showToast('Template deleted');
            });
        });

        

        

        var _tplPreviewBuilt = false;
        var _tplPreviewState = null;
        function ensureTplPreviewModal() {
            if (_tplPreviewBuilt) return;
            $('body').append(
                '<div class="impulse-scene-preview-modal" id="impulse-tpl-preview-modal" style="display:none">'
                  + '<div class="impulse-scene-preview-backdrop" id="impulse-tpl-preview-backdrop"></div>'
                  + '<div class="impulse-scene-preview-dialog">'
                    + '<div class="impulse-scene-preview-stage" id="impulse-tpl-preview-stage"></div>'
                    + '<button type="button" class="impulse-x-btn impulse-scene-preview-close" id="impulse-tpl-preview-close" title="Close (Esc)"><svg viewBox="0 0 24 24" width="10" height="10" stroke="currentColor" fill="none" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>'
                    + '<button type="button" class="impulse-scene-preview-fab" id="impulse-tpl-preview-fab">Use this template &rarr;</button>'
                  + '</div>'
                + '</div>'
            );
            _tplPreviewBuilt = true;
        }
        function closeTplPreview() {
            var $m = $('#impulse-tpl-preview-modal');
            if (!$m.length) return;
            $m.hide();
            $('#impulse-tpl-preview-stage').empty();
            _tplPreviewState = null;
        }
        function openTplPreview(template) {
            if (!template || !template.html_preview) return false;
            ensureTplPreviewModal();
            var $modal = $('#impulse-tpl-preview-modal');
            var $stage = $('#impulse-tpl-preview-stage');
            _tplPreviewState = template;
            $stage.empty();

            
            
            $modal.css('display', 'flex');
            var doMount = function() {
                var stageEl = $stage[0];
                if (!stageEl) return;
                var w = stageEl.clientWidth;
                if (!w) return; 

                

                
                var slot = document.createElement('div');
                slot.style.cssText = 'position:relative;width:100%;overflow:hidden;background:#0a0c0e';
                $stage.append(slot);
                var maxH = Math.floor(window.innerHeight * 0.88);
                mountLibraryPreviewIframe(slot, template.html_preview, {
                    animated: true,
                    fallbackWidth: w,
                    maxScaledHeight: maxH
                });
                var iframe = slot.querySelector('iframe');
                if (iframe) iframe.style.pointerEvents = 'auto';
            };
            
            requestAnimationFrame(function() { requestAnimationFrame(doMount); });
            return true;
        }
        $(document).on('click', '#impulse-tpl-preview-close, #impulse-tpl-preview-backdrop', closeTplPreview);
        $(document).on('keydown.tplpreview', function(e) {
            if (e.key === 'Escape' && $('#impulse-tpl-preview-modal').is(':visible')) closeTplPreview();
        });

        var _tplPreviewBypass = false;
        $(document).on('click', '#impulse-tpl-preview-fab', function() {
            var template = _tplPreviewState;
            if (!template) return;
            var src = template.source || 'local';
            closeTplPreview();
            _tplPreviewBypass = true;
            var $tile = $('.impulse-my-template-item[data-template-id="' + template.id + '"][data-source="' + src + '"]').first();
            if ($tile.length) $tile.click();
            else _tplPreviewBypass = false;
        });

        $(document).on('click', '.impulse-my-template-item', function(e) {
            if ($(e.target).closest('.template-delete, .template-upload').length) return;

            var id = $(this).data('template-id');
            var source = $(this).data('source') || 'local';
            var pool = source === 'platform' ? getPlatformSections() : getUserTemplates();
            var template = pool.find(function(t) { return t.id === id; });

            if (!template || !Impulse.pageId) return;

            
            if (!_tplPreviewBypass) {
                
                if (typeof hoverTimeout !== 'undefined' && hoverTimeout) clearTimeout(hoverTimeout);
                if (typeof $hoverPreview !== 'undefined' && $hoverPreview && $hoverPreview.length) $hoverPreview.hide();
                if (openTplPreview(template)) return;
                
            }
            _tplPreviewBypass = false;

            
            if (template.tier === 'pro' && window.isProLocked && window.isProLocked()) {
                if (window.showProUpgradePrompt) {
                    window.showProUpgradePrompt(template.name + ' template');
                }
                return;
            }

            var containerTypes = ['section',  'rows', 'columns', 'slider', 'modal'];
            var rootOnlyTypes = ['modal'];
            var parentId = 0;
            var siblingId = null;
            var siblingPosition = null;
            var tType = template.type || template.elementType;
            
            if (selectedCellGridParentId && selectedCellGridCellKey) {
                if (forbiddenInCells.indexOf(tType) !== -1) return;
                parentId = selectedCellGridParentId;
            } else if (selectedGridParentId) {
                if (forbiddenInCells.indexOf(tType) !== -1) return;
                parentId = selectedGridParentId;
            } else if (selectedElementId && selectedElementType) {
                if (containerTypes.indexOf(selectedElementType) !== -1) {
                    if (rootOnlyTypes.indexOf(tType) !== -1) return;
                    if ((selectedElementType === 'rows' || selectedElementType === 'columns' || selectedElementType === 'grid') && 
                        forbiddenInCells.indexOf(tType) !== -1) return;
                    parentId = selectedElementId;
                } else {
                    siblingId = selectedElementId;
                    siblingPosition = 'after';
                }
            }

            if (template.children && template.children.length > 0) {
                var treeData = {
                    type: template.type,
                    settings: template.settings,
                    children: template.children
                };
                
                if (siblingId) {
                    
                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({
                            element_type: template.type,
                            settings: template.settings || {},
                            sibling_id: siblingId,
                            insert_position: siblingPosition
                        }),
                        success: function(resp) {
                            if (resp.id && template.children.length) {
                                var i = 0;
                                function insertNext() {
                                    if (i >= template.children.length) {
                                        window.showToast('Template inserted');
                                        refreshPreview();
                                        setTimeout(updateStructureTree, 300);
                                        return;
                                    }
                                    insertTemplateElements(template.children[i], resp.id, function() {
                                        i++;
                                        insertNext();
                                    });
                                }
                                insertNext();
                            } else {
                                window.showToast('Template inserted');
                                refreshPreview();
                                setTimeout(updateStructureTree, 300);
                            }
                        },
                        error: function() { window.showToast('Failed to insert template'); }
                    });
                } else {
                    insertTemplateElements(treeData, parentId, function() {
                        window.showToast('Template inserted');
                        refreshPreview();
                        setTimeout(updateStructureTree, 300);
                    });
                }
            } else {
                
                var postData = {
                    element_type: template.type,
                    settings: template.settings
                };
                if (siblingId) {
                    postData.sibling_id = siblingId;
                    postData.insert_position = siblingPosition;
                } else {
                    postData.parent_id = parentId;
                }
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                    method: 'POST',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function(resp) {
                        window.showToast('Template inserted');
                        refreshPreview();
                        setTimeout(updateStructureTree, 300);
                    },
                    error: function() {
                        window.showToast('Failed to insert template');
                    }
                });
            }
        });

        $(document).on('dragstart', '.impulse-my-template-item', function(e) {
            var id = $(this).data('template-id');
            var source = $(this).data('source') || 'local';
            var pool = source === 'platform' ? getPlatformSections() : getUserTemplates();
            var template = pool.find(function(t) { return t.id === id; });
            
            if (template && template.tier === 'pro' && window.isProLocked && window.isProLocked()) {
                e.preventDefault();
                if (window.showProUpgradePrompt) window.showProUpgradePrompt(template.name + ' template');
                return false;
            }
            if (template) {
                var payload = JSON.stringify({
                    type: 'user-template',
                    templateId: id,
                    elementType: template.type,
                    settings: template.settings,
                    children: template.children || []
                });
                draggedElement = payload;
                draggedTemplate = null;
                e.originalEvent.dataTransfer.setData('text/plain', payload);
                e.originalEvent.dataTransfer.effectAllowed = 'copy';
                $(this).addClass('dragging');
                isDragActive = true; 
                $('.impulse-canvas').addClass('drag-active');
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({ 
                        type: 'impulse-drag-start',
                        element: payload,
                        template: null
                    }, '*');
                }
            }
        });
        
        $(document).on('dragend', '.impulse-my-template-item', function(e) {
            $(this).removeClass('dragging');
            $('.impulse-canvas').removeClass('drag-over drag-active');
            isDragActive = false;
            if (pendingRefresh) { pendingRefresh = false; refreshPreview(); }
            
            var element = draggedElement;
            setTimeout(function() {
                if (!window._dropHandled && element && lastDragPosition.fromIframe) {
                    var iframe = document.getElementById('impulse-iframe');
                    if (iframe && iframe.contentWindow) {
                        iframe.contentWindow.postMessage({ 
                            type: 'impulse-find-drop-at-position',
                            element: element,
                            template: null,
                            x: lastDragPosition.x,
                            y: lastDragPosition.y
                        }, '*');
                    }
                }
                window._dropHandled = false;
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({ type: 'impulse-drag-end' }, '*');
                }
            }, 100);
            
            draggedElement = null;
            draggedTemplate = null;
            lastDragPosition = { x: 0, y: 0, fromIframe: false };
        });

        loadUserTemplates(function() {
            renderUserTemplates();
        });

        function copyStyle() {
            if (!selectedElementId) {
                window.showToast('Select an element first');
                return;
            }
            
            function _saveStyleClipboard(data) {
                styleClipboard = data;
                try { sessionStorage.setItem('impulse_style_clipboard', JSON.stringify(data)); } catch(e) {}
                window.showToast('Style copied');
            }

            
            var panelId = $('.impulse-panel-right').data('element-id');
            if (panelId && String(panelId) === String(selectedElementId)) {
                _saveStyleClipboard({
                    type: selectedElementType,
                    settings: collectSettingsFromPanel()
                });
            } else {
                $.ajax({
                    url: Impulse.api + 'elements/' + selectedElementId,
                    method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    success: function(data) {
                        _saveStyleClipboard({
                            type: data.type || data.section_type || selectedElementType,
                            settings: data.settings || {}
                        });
                    }
                });
            }
        }

        function pasteStyle() {
            if (!styleClipboard) {
                window.showToast('No style to paste');
                return;
            }
            if (!selectedElementId) {
                window.showToast('Select an element first');
                return;
            }

            
            var excludeProps = [
                
                'content', 'text', 'title', 'items', 'label', 'placeholder', 'description',

                
                
                'title_content', 'text_content', 'icon', 'icon_image', 'icon_svg', 'icon_url',

                
                'slides', 'plans', 'code', 'fields', 'cells', 'cards',
                'features', 'benefits', 'badges', 'menu', 'tabs', 'reviews',
                'front_title', 'front_content', 'back_title', 'back_content', 'back_button_text', 'back_button_link',
                'la_text', 'la_image_src', 'la_content_type', 'la_preset',
                'pl_items', 'countdown_date',

                

                
                'custom_lines', 'phrases', 'raw_text',
                
                'image_id', 'image_url', 'image_src', 'bg_image', 'gallery_images', 'images',
                'video_url', 'video_id', 'poster',
                'svg', 'viewbox', 'graphic_type',
                
                'link', 'url', 'href', 'button_link', 'button_url',
                
                '_cell_row', '_cell_col', 'rows', '_selected_cells',
                'columns', 'layout', 'layout_type', 'mobile_layout',
                
                'product_id', 'product_ids', 'category_id', 'shortcode',
                'font_family',
                
                'form_fields', 'form_action', 'form_email', 'success_message',
                
                'map_lat', 'map_lng', 'map_address', 'map_zoom',
                
                'la_duration', 'la_delay', 'la_flash', 'la_scroll_trigger',
                'entrance_animation', 'entrance_intensity', 'animation_duration', 'unveil_direction'
            ];

            

            
            
            var contentSuffixes = [
                '_text', '_content', '_title', '_label', '_items', '_slides',
                '_cards', '_url', '_link', '_html', '_code', '_caption',
                '_message', '_name', '_heading', '_subtitle', '_tagline',
                '_description', '_quote', '_author', '_address'
            ];

            
            var contentVariantSuffixes = ['_mobile', '_tablet'];
            function isContentVariantOf(prop, baseList) {
                for (var i = 0; i < contentVariantSuffixes.length; i++) {
                    var v = contentVariantSuffixes[i];
                    if (!prop.endsWith(v)) continue;
                    var base = prop.slice(0, -v.length);
                    if (baseList.indexOf(base) !== -1) return true;
                    for (var j = 0; j < contentSuffixes.length; j++) {
                        if (base.endsWith(contentSuffixes[j])) return true;
                    }
                }
                return false;
            }
            function isContentProp(prop) {
                if (excludeProps.indexOf(prop) !== -1) return true;
                for (var i = 0; i < contentSuffixes.length; i++) {
                    if (prop.endsWith(contentSuffixes[i])) return true;
                }
                if (isContentVariantOf(prop, excludeProps)) return true;
                
                if (prop === 'line_1') return true;
                return false;
            }

            var newSettings = {};
            var src = styleClipboard.settings;
            for (var prop in src) {
                if (!src.hasOwnProperty(prop)) continue;
                if (isContentProp(prop)) continue;
                newSettings[prop] = src[prop];
            }
            
            if (Object.keys(newSettings).length === 0) {
                window.showToast('No style properties to paste');
                return;
            }

            

            

            

            

            
            function _runPut(settingsToPut) {
                $.ajax({
                    url: Impulse.api + 'elements/' + selectedElementId,
                    method: 'PUT',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ settings: settingsToPut, page_id: Impulse.pageId }),
                    success: function() {
                        window.showToast('Style pasted');
                        
                        var existing = $('.impulse-panel-right').data('existing-settings') || {};
                        for (var k in newSettings) {
                            if (newSettings.hasOwnProperty(k)) existing[k] = newSettings[k];
                        }
                        $('.impulse-panel-right').data('existing-settings', existing);

                        

                        

                        
                        
                        if (window.impulseCSSVars && typeof window.impulseCSSVars.apply === 'function') {
                            try { window.impulseCSSVars.apply(selectedElementId, existing); } catch (_e) {}
                        }

                        

                        

                        
                        refreshElement(selectedElementId);
                        
                        openSettings(selectedElementId, selectedElementType);
                    }
                });
            }

            

            
            $.ajax({
                url: Impulse.api + 'elements/' + selectedElementId,
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                success: function(tgt) {
                    var existingTarget = (tgt && tgt.settings) ? tgt.settings : {};
                    var merged = $.extend({}, existingTarget);
                    for (var sk in newSettings) {
                        if (newSettings.hasOwnProperty(sk)) merged[sk] = newSettings[sk];
                    }
                    _runPut(merged);
                },
                error: function() {
                    _runPut(newSettings);
                }
            });
        }

        

        
        
        function applyStyleToAllSameType(sourceId, sourceType, scope) {
            if (!sourceId || !sourceType) return;
            scope = (scope === 'screen') ? 'screen' : 'page';
            var _ifr = document.getElementById('impulse-iframe');
            var _doc = _ifr && (_ifr.contentDocument || (_ifr.contentWindow && _ifr.contentWindow.document));
            if (!_doc) return;

            
            var _wrapper = _doc.querySelector('.impulse-content-wrapper');
            var _screens = _wrapper ? _wrapper.querySelectorAll(':scope > .impulse-el[data-type="section"]') : [];
            function _screenOf(el) {
                if (!el) return null;
                for (var _si = 0; _si < _screens.length; _si++) {
                    if (_screens[_si] === el || _screens[_si].contains(el)) return _screens[_si];
                }
                return null;
            }
            var _srcScreen = (scope === 'screen')
                ? _screenOf(_doc.querySelector('.impulse-el[data-id="' + sourceId + '"]')) : null;
            var _scopeLabel = (scope === 'screen') ? ' on this screen' : '';
            var targetIds = [];
            _doc.querySelectorAll('.impulse-el[data-type="' + sourceType + '"]').forEach(function(el) {
                var id = el.getAttribute('data-id');
                if (!id || String(id) === String(sourceId) || targetIds.indexOf(id) !== -1) return;
                if (scope === 'screen' && _srcScreen && _screenOf(el) !== _srcScreen) return;
                targetIds.push(id);
            });
            if (!targetIds.length) { window.showToast && window.showToast('No other ' + sourceType + 's' + _scopeLabel); return; }

            function _styleOnly(src) {
                var exclude = ['content','text','title','items','label','placeholder','description',
                    'title_content','text_content','icon','icon_image','icon_svg','icon_url',
                    'slides','plans','code','fields','cells','cards','features','benefits','badges','menu','tabs',
                    'front_title','front_content','back_title','back_content','back_button_text','back_button_link',
                    'la_text','la_image_src','la_content_type','la_preset','pl_items','countdown_date',
                    'custom_lines','phrases','raw_text',
                    'image_id','image_url','image_src','bg_image','gallery_images','images','video_url','video_id','poster',
                    'svg','viewbox','graphic_type','link','url','href','button_link','button_url',
                    '_cell_row','_cell_col','rows','_selected_cells','columns','layout','layout_type','mobile_layout',
                    'product_id','product_ids','category_id','shortcode','font_family',
                    'form_fields','form_action','form_email','success_message',
                    'map_lat','map_lng','map_address','map_zoom',
                    'la_duration','la_delay','la_flash','la_scroll_trigger',
                    'entrance_animation','entrance_intensity','animation_duration','unveil_direction'];
                var cSuf = ['_text','_content','_title','_label','_items','_slides','_cards','_url','_link','_html','_code','_caption','_message','_name','_heading','_subtitle','_tagline','_description','_quote','_author','_address'];
                var vSuf = ['_mobile','_tablet'];

                

                var _kineticStyle = (sourceType === 'kinetic' || sourceType === 'title')
                    ? ['la_preset','la_duration','la_delay','la_flash','la_scroll_trigger'] : [];
                function isContent(prop) {
                    if (_kineticStyle.indexOf(prop) !== -1) return false;
                    if (exclude.indexOf(prop) !== -1) return true;
                    var i;
                    for (i = 0; i < cSuf.length; i++) { if (prop.endsWith(cSuf[i])) return true; }
                    for (i = 0; i < vSuf.length; i++) {
                        var v = vSuf[i];
                        if (prop.endsWith(v)) {
                            var base = prop.slice(0, -v.length);
                            if (exclude.indexOf(base) !== -1) return true;
                            for (var k = 0; k < cSuf.length; k++) { if (base.endsWith(cSuf[k])) return true; }
                        }
                    }
                    if (prop === 'line_1') return true;
                    return false;
                }
                var out = {};
                for (var prop in src) { if (src.hasOwnProperty(prop) && !isContent(prop)) out[prop] = src[prop]; }
                return out;
            }

            function _finish(ok, total) {
                if (typeof refreshPreview === 'function') refreshPreview();
                window.showToast && window.showToast('Style applied to ' + ok + ' of ' + total + ' ' + sourceType + 's' + _scopeLabel);
            }
            function _applyTo(srcSettings) {
                var styleOnly = _styleOnly(srcSettings || {});

                

                var _srcLineColors = null;
                if ((sourceType === 'kinetic' || sourceType === 'title') && srcSettings && srcSettings.custom_lines) {
                    try {
                        var _scl = (typeof srcSettings.custom_lines === 'string') ? JSON.parse(srcSettings.custom_lines) : srcSettings.custom_lines;
                        if (Array.isArray(_scl) && _scl.length) _srcLineColors = _scl.map(function(l){ return l && l.color; });
                    } catch (e) {}
                }
                if (!Object.keys(styleOnly).length && !_srcLineColors) { window.showToast && window.showToast('No style to apply'); return; }
                var total = targetIds.length, ok = 0, idx = 0;
                window.showToast && window.showToast('Applying style to ' + total + ' ' + sourceType + 's...');

                

                
                
                function _next() {
                    if (idx >= total) { _finish(ok, total); return; }
                    var tid = targetIds[idx++];
                    $.ajax({
                        url: Impulse.api + 'elements/' + tid, method: 'GET',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        success: function(tgt) {
                            var merged = $.extend({}, (tgt && tgt.settings) || {});
                            for (var k in styleOnly) { if (styleOnly.hasOwnProperty(k)) merged[k] = styleOnly[k]; }

                            
                            if (_srcLineColors && merged.custom_lines) {
                                try {
                                    var _tcl = (typeof merged.custom_lines === 'string') ? JSON.parse(merged.custom_lines) : merged.custom_lines;
                                    if (Array.isArray(_tcl) && _tcl.length) {
                                        for (var _li = 0; _li < _tcl.length; _li++) {
                                            var _lc = (_srcLineColors[_li] !== undefined) ? _srcLineColors[_li] : _srcLineColors[_srcLineColors.length - 1];
                                            if (_lc && _tcl[_li]) _tcl[_li].color = _lc;
                                        }
                                        merged.custom_lines = JSON.stringify(_tcl);
                                    }
                                } catch (e) {}
                            }
                            $.ajax({
                                url: Impulse.api + 'elements/' + tid, method: 'PUT',
                                headers: { 'X-WP-Nonce': Impulse.nonce }, contentType: 'application/json',
                                data: JSON.stringify({ settings: merged, page_id: Impulse.pageId }),
                                success: function() { ok++; },
                                complete: function() { _next(); }
                            });
                        },
                        error: function() { _next(); }
                    });
                }
                _next();
            }

            
            var _panelId = $('.impulse-panel-right').data('element-id');
            if (_panelId && String(_panelId) === String(sourceId) && typeof collectSettingsFromPanel === 'function') {
                _applyTo(collectSettingsFromPanel());
            } else {
                $.ajax({
                    url: Impulse.api + 'elements/' + sourceId, method: 'GET',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    success: function(d) { _applyTo((d && d.settings) || {}); },
                    error: function() { window.showToast && window.showToast('Could not read source style'); }
                });
            }
        }

        function showToast(message, undoCallback) {
            var html = '<div class="impulse-toast">' + message;
            if (undoCallback) {
                html += ' <span class="impulse-toast-undo" style="cursor:pointer;text-decoration:underline;margin-left:8px">Undo</span>';
            }
            html += '</div>';
            var $toast = $(html);
            if (undoCallback) {
                $toast.find('.impulse-toast-undo').on('click', function() {
                    undoCallback();
                    $toast.remove();
                });
            }
            $('body').append($toast);
            setTimeout(function() {
                $toast.fadeOut(300, function() { $(this).remove(); });
            }, undoCallback ? 5000 : 2000);
        }

        
        
        var $contextMenu = $('#impulse-context-menu');
        
        function buildContextMenu(ctx) {
            var h = '';
            var hasClip = !!getClipboard();

            
            
            if (ctx.cell) {
                if (ctx.cell.gridType === 'grid') {
                    h += ctxItem('dup-row', 'Duplicate Row');
                    h += ctxDiv();
                } else {
                    h += ctxItem('dup-cell', 'Duplicate Cell');
                    h += ctxItem('del-cell', 'Delete Cell');
                    h += ctxDiv();
                    h += ctxItem('dup-row', 'Duplicate Row');
                    h += ctxItem('del-row', 'Delete Row');
                    h += ctxDiv();
                }
            }

            if (ctx.element) {
                if (ctx.parent) {
                    h += ctxItem('edit-container', 'Select Parent');
                }

                

                var _moLabels = { grid:'Grid', rows:'Rows', columns:'Columns', section:'Section' };
                if (ctx.parent && ctx.grandparent && _moLabels[ctx.parent.type]) {
                    h += ctxItem('move-out', 'Move Out of ' + _moLabels[ctx.parent.type]);
                }
                
                var _dupLabel = ctx.inSlider ? 'Duplicate Slide' : 'Duplicate';
                h += ctxItem('duplicate', _dupLabel, '^+D');

                
                
                var _msCount = (window._impMultiSel && window._impMultiSel.length >= 2) ? window._impMultiSel.length
                             : ((ctx.multiSel && ctx.multiSel.length >= 2) ? ctx.multiSel.length : 0);
                if (_msCount >= 2) {
                    h += ctxDiv();
                    h += ctxItem('wrap-selection-section', 'Wrap ' + _msCount + ' in Section');
                    h += ctxItem('wrap-selection-rows',    'Wrap ' + _msCount + ' in Rows');
                    h += ctxItem('wrap-selection-columns', 'Wrap ' + _msCount + ' in Columns');
                    h += ctxItem('wrap-selection-grid',    'Wrap ' + _msCount + ' in Grid');
                } else if (['section','header','footer'].indexOf(ctx.element.type) === -1) {

                    

                    
                    h += ctxDiv();
                    h += ctxItem('wrap-section', 'Wrap in Section');
                }

                
                if (ctx.element.type === 'grid') {
                    h += ctxDiv();
                    h += ctxItem('convert-grid-to-rows', 'Convert to Rows');
                }

                if (ctx.element.type === 'title') {
                    h += ctxDiv();
                    h += ctxItem('convert-to-kinetic', 'Convert to Kinetic');
                }

                
                if (['section','header','footer'].indexOf(ctx.element.type) === -1) {
                    h += ctxDiv();
                    h += ctxItem('block-reveal', 'Reveal…');

                    
                    var _pbOn = !!(ctx.element.settings && (ctx.element.settings.push_bottom === '1' || ctx.element.settings.push_bottom === true));
                    h += ctxItem('toggle-push-bottom', (_pbOn ? '✓ ' : '') + 'Push to bottom');
                }
                h += ctxDiv();
                h += ctxItem('copy', 'Copy', '^+C');
                h += ctxItem('paste', 'Paste', '^+V', hasClip ? '' : 'disabled');
                h += ctxDiv();
                h += ctxItem('copy-style', 'Copy Style', '^+\u21e7+C');
                h += ctxItem('paste-style', 'Paste Style', '^+\u21e7+V', styleClipboard ? '' : 'disabled');
                var _aslType = (ctx.element && ctx.element.type) || '';

                
                var _aslNames = { icon_card:'Icon Card', price_list:'Price List', flip_box:'Flip Box',
                    product_carousel:'Product Carousel', order_summary:'Order Summary', icon_text:'Icon Text' };
                var _aslLabel = _aslNames[_aslType] || (_aslType
                    ? _aslType.replace(/_/g, ' ').replace(/\b\w/g, function(c){ return c.toUpperCase(); })
                    : 'Element');
                var _aslPlural = /s$/i.test(_aslLabel) ? _aslLabel : _aslLabel + 's';
                
                var _aslScreen = _impScNoun();
                var _aslScreens = _impScNoun('PLURAL');
                h += ctxItem('paste-style-screen', 'Apply Style to ' + _aslPlural + ' on This ' + _aslScreen);
                h += ctxItem('paste-style-all', 'Apply Style to ' + _aslPlural + ' on All ' + _aslScreens);
                h += ctxItem('reset-style', 'Reset Style');
                h += ctxDiv();

                

                
                var _isSceneModePage = Impulse.pageSettings && (
                    true
                );
                var _isTopLevelSection = (ctx.element.type === 'section') && !ctx.parent;
                if (!(_isSceneModePage && _isTopLevelSection)) {
                    h += ctxItem('save-template', 'Save to Library');
                }
                h += ctxItem('insert-from-library', 'Insert from Library');
                h += ctxItem('edit-with-instagent', 'Edit with Instagent');
                h += ctxDiv();
                h += ctxItem('save-default', 'Save as Default');
                h += ctxDiv();

                
                h += ctxItem('toggle-hide-mobile', ctx.element.hiddenMobile ? 'Show on mobile' : 'Hide on mobile');
                h += ctxDiv();
                h += ctxItem('structure', 'Structure', '^+I');
                h += ctxItem('delete', 'Delete', 'Del', 'danger');
            }

            if (h) h += ctxDiv();
            h += ctxItem('export-page', 'Export Page');
            h += ctxItem('import-page', 'Import Page');

            return h;
        }

        
        
        var cellStyleClipboard = null;
        var cellStyleClipboardSrc = null; 
        function buildCellContextMenu(ctx) {
            if (!ctx || !ctx.gridCell) return '';

            
            var n = (parseInt(ctx.gridCell.cellIdx) || 0) + 1;
            var pasteLabel = cellStyleClipboard
                ? ('Paste Style from Cell ' + cellStyleClipboardSrc + ' to Cell ' + n)
                : 'Paste Cell Style';
            var h = '';
            h += ctxItem('cell-copy-style', 'Copy Cell ' + n + ' Style');
            h += ctxItem('cell-paste-style', pasteLabel, '', cellStyleClipboard ? '' : 'disabled');
            h += ctxDiv();
            h += ctxItem('cell-apply-style-all', 'Apply Cell ' + n + ' Style to All Cells');
            h += ctxItem('cell-reset-style', 'Reset Cell ' + n + ' Style');

            
            if (ctx.gridCell.gridType === 'grid') {
                h += ctxDiv();
                h += ctxItem('convert-grid-to-rows', 'Convert Grid to Rows');
            }
            return h;
        }

        
        
        function _cellSuffixMatch(key, idx) {

            
            var devs = ['', '_tablet', '_mobile'];
            for (var i = 0; i < devs.length; i++) {
                var sfx = '_' + idx + devs[i];
                if (key.length > sfx.length && key.slice(-sfx.length) === sfx) {
                    return { dev: devs[i], base: key.slice(0, -sfx.length) };
                }
            }
            return null;
        }
        function _collectCellStyles(settings, idx) {
            var out = {};
            for (var key in settings) {
                if (key.indexOf('cell_') !== 0) continue;
                var m = _cellSuffixMatch(key, idx);
                if (m) out[m.base + m.dev] = settings[key];
            }
            return out;
        }
        function _expandCellStyles(styleMap, idx) {
            var update = {};
            for (var base in styleMap) {
                var dm = base.match(/_(tablet|mobile)$/);
                if (dm) {
                    update[base.slice(0, -dm[0].length) + '_' + idx + dm[0]] = styleMap[base];
                } else {
                    update[base + '_' + idx] = styleMap[base];
                }
            }
            return update;
        }
        function _saveGridSettings(gridId, merged, gridType) {
            $('.impulse-panel-right').data('existing-settings', merged);
            enqueueSave(gridId, merged, function(ok) {
                if (!ok) return;

                

                
                
                if (window.refreshPreview) window.refreshPreview();
                else refreshElement(gridId);
            });
        }
        function applyCellStyleToAll(gridId, srcIdx, gridType) {
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            var cols = parseInt(settings.columns) || 2;
            var rows = parseInt(settings.rows) || 2;
            var total = cols * rows;
            var srcStyles = _collectCellStyles(settings, srcIdx);
            var update = $.extend({}, settings);
            for (var i = 0; i < total; i++) {
                if (i === srcIdx) continue;

                

                
                
                for (var key in update) {
                    if (key.indexOf('cell_') !== 0) continue;
                    if (_cellSuffixMatch(key, i)) update[key] = '';
                }
                
                $.extend(update, _expandCellStyles(srcStyles, i));
            }
            _saveGridSettings(gridId, update, gridType);
            if (window.showToast) showToast('Applied cell style to ' + (total - 1) + ' other cells');
        }
        function copyCellStyle(gridId, idx) {
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            cellStyleClipboard = _collectCellStyles(settings, idx);
            cellStyleClipboardSrc = idx + 1;
            if (window.showToast) showToast('Cell ' + cellStyleClipboardSrc + ' style copied');
        }
        function pasteCellStyle(gridId, idx, gridType) {
            if (!cellStyleClipboard) return;
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            var update = $.extend({}, settings, _expandCellStyles(cellStyleClipboard, idx));
            _saveGridSettings(gridId, update, gridType);
            if (window.showToast) showToast('Pasted to Cell ' + (idx + 1));
        }
        function resetCellStyle(gridId, idx, gridType) {

            
            var settings = $('.impulse-panel-right').data('existing-settings') || {};
            var update = $.extend({}, settings);
            var cleared = 0;
            for (var key in settings) {
                if (key.indexOf('cell_') !== 0) continue;
                if (_cellSuffixMatch(key, idx)) { update[key] = ''; cleared++; }
            }
            _saveGridSettings(gridId, update, gridType);
            if (window.showToast) showToast('Reset Cell ' + (idx + 1) + ' (' + cleared + ' settings cleared)');
        }

        

        

        

        $('.impulse-store-left, .impulse-panel-right, .impulse-page-list, .impulse-structure-tree').on('scroll', function() {
            if (window._ctxJustShown) return;
            ctxHide();
        });
        $(window).on('message', function(e) {
            var d = e.originalEvent ? e.originalEvent.data : e.data;
            if (!d || !d.type) return;
            if (d.type === 'impulse-deselect' ||
                d.type === 'impulse-drag-active' || d.type === 'impulse-scroll' ||
                d.type === 'impulse-dismiss-menu') {
                ctxHide();
            } else if (d.type === 'impulse-select') {

                
                if (!window._ctxJustShown) ctxHide();
            }
        });

        

        

        

        

        function toggleBlockLayoutFlag(id, key, label) {
            $.ajax({
                url: Impulse.api + 'elements/' + id, method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                success: function(el) {
                    var s = (el && el.settings) || {};
                    var on = (s[key] === '1' || s[key] === 1 || s[key] === true);
                    var merged = $.extend({}, s); merged[key] = on ? '' : '1';
                    if (typeof enqueueSave === 'function') {
                        enqueueSave(id, merged, function(){ if (typeof refreshElement === 'function') refreshElement(id); });
                    }
                    (window.showToast || function(){})(label + (on ? ' off' : ' on'), 'success');
                },
                error: function() { (window.showToast || function(){})('Could not update block.', 'error'); }
            });
        }
        function openBlockRevealModal(id, type) {
            $.ajax({
                url: Impulse.api + 'elements/' + id, method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                success: function(el) { _showBlockRevealModal(id, (el && el.settings) || {}); },
                error: function() { (window.showToast || function(){})('Could not load block.', 'error'); }
            });
        }
        function _showBlockRevealModal(id, s) {
            $('#impulse-block-reveal-modal').remove();
            var order = (s.reveal_order !== undefined && s.reveal_order !== '' && s.reveal_order !== null) ? parseInt(s.reveal_order, 10) : '';
            var delay = s.reveal_delay ? parseInt(s.reveal_delay, 10) : 0;
            var off   = (s.reveal_off === '1' || s.reveal_off === true);
            var C = { bg:'#1a1d21', card:'#22262b', line:'#3a3f45', txt:'#e0e0e0', dim:'#999' };
            var inputCss = 'width:62px;background:'+C.bg+';border:1px solid '+C.line+';color:'+C.txt+';border-radius:4px;padding:4px 6px;font-size:12px;text-align:center;font-family:Arial,Helvetica,sans-serif';
            var html = ''
              + '<div id="impulse-block-reveal-modal" style="position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.55)">'
              + '<div style="width:300px;background:'+C.card+';border:1px solid '+C.line+';border-radius:8px;padding:16px;box-shadow:0 12px 40px rgba(0,0,0,0.5);font-family:Arial,Helvetica,sans-serif;color:'+C.txt+'">'
              + '<div style="font-size:13px;font-weight:600;margin-bottom:3px">Block Reveal</div>'
              + '<div style="font-size:11px;color:'+C.dim+';line-height:1.45;margin-bottom:13px">Order this block within its section’s reveal. Takes effect when the section has a reveal effect.</div>'
              + '<label style="display:flex;align-items:center;gap:8px;font-size:12px;margin-bottom:13px;cursor:pointer"><input type="checkbox" id="ibr-off"'+(off?' checked':'')+'> Appear immediately (skip reveal)</label>'
              + '<div id="ibr-fields" style="display:'+(off?'none':'block')+'">'
              + '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:9px"><label style="font-size:11px;color:'+C.dim+'">Order <span style="opacity:0.65">0 first → 10 last</span></label><input type="number" id="ibr-order" min="0" max="10" step="1" value="'+(order===''?'':order)+'" placeholder="auto" style="'+inputCss+'"></div>'
              + '<div style="display:flex;align-items:center;justify-content:space-between"><label style="font-size:11px;color:'+C.dim+'">Delay <span style="opacity:0.65">ms</span></label><input type="number" id="ibr-delay" min="0" max="2000" step="50" value="'+delay+'" style="'+inputCss+'"></div>'
              + '</div>'
              + '<div style="display:flex;gap:8px;margin-top:16px;justify-content:flex-end">'
              + '<button type="button" id="ibr-cancel" style="height:28px;padding:0 12px;background:transparent;border:1px solid '+C.line+';color:'+C.dim+';border-radius:4px;font-size:12px;cursor:pointer">Cancel</button>'
              + '<button type="button" id="ibr-apply" style="height:28px;padding:0 14px;background:'+C.txt+';border:1px solid '+C.txt+';color:'+C.bg+';border-radius:4px;font-size:12px;font-weight:600;cursor:pointer">Apply</button>'
              + '</div></div></div>';
            var $m = $(html).appendTo(document.body);
            $m.data('settings', s);
            $m.find('#ibr-off').on('change', function(){ $m.find('#ibr-fields').css('display', this.checked ? 'none' : 'block'); });
            $m.on('mousedown', function(e){ if (e.target === this) $m.remove(); });
            $m.find('#ibr-cancel').on('click', function(){ $m.remove(); });
            $m.find('#ibr-apply').on('click', function(){
                var offV = $m.find('#ibr-off').is(':checked');
                var ordRaw = $.trim(String($m.find('#ibr-order').val()));
                var ordV = (offV || ordRaw === '') ? '' : Math.max(0, Math.min(10, parseInt(ordRaw, 10) || 0));
                var dlyV = offV ? 0 : Math.max(0, Math.min(2000, parseInt($m.find('#ibr-delay').val(), 10) || 0));
                var merged = $.extend({}, $m.data('settings') || {}, { reveal_off: offV ? '1' : '', reveal_order: ordV, reveal_delay: dlyV });
                if (typeof enqueueSave === 'function') {
                    enqueueSave(id, merged, function(){ if (typeof refreshElement === 'function') refreshElement(id); });
                }
                (window.showToast || function(){})('Reveal updated', 'success');
                $m.remove();
            });
        }

        $(document).on('click', '.impulse-context-item', function() {
            var action = $(this).data('action');
            if (!action || action.indexOf('grid-') === 0 || action.indexOf('p-') === 0) return;
            var ctx = _ctxData || {};

            if (ctx.gridCell && (action.indexOf('cell-') === 0 || action === 'convert-grid-to-rows')) {
                ctxHide();
                var gc = ctx.gridCell;
                if (action === 'cell-copy-style')        copyCellStyle(gc.gridId, gc.cellIdx);
                else if (action === 'cell-paste-style')  pasteCellStyle(gc.gridId, gc.cellIdx, gc.gridType);
                else if (action === 'cell-apply-style-all') applyCellStyleToAll(gc.gridId, gc.cellIdx, gc.gridType);
                else if (action === 'cell-reset-style')  resetCellStyle(gc.gridId, gc.cellIdx, gc.gridType);
                else if (action === 'convert-grid-to-rows') convertGridToRows(gc.gridId);
                return;
            }

            switch(action) {
                case 'edit-container':
                    if (ctx.parent) {
                        
                        var _ecIframe = document.getElementById('impulse-iframe');
                        if (_ecIframe && _ecIframe.contentDocument) {
                            var _ecEl = _ecIframe.contentDocument.querySelector('.impulse-el[data-id="' + ctx.parent.id + '"]');
                            if (_ecEl) {
                                _ecIframe.contentDocument.querySelectorAll('.impulse-el.selected').forEach(function(x) { x.classList.remove('selected'); });
                                _ecEl.classList.add('selected');
                            }
                        }
                        openSettings(ctx.parent.id, ctx.parent.type);
                    }
                    break;
                case 'move-out':

                    
                    
                    if (ctx.element && ctx.element.id && ctx.grandparent && ctx.grandparent.id) {
                        moveElementInto(ctx.element.id, ctx.grandparent.id, null, null, null, null, true);
                    }
                    break;
                case 'copy':
                    copyElement();
                    break;
                case 'paste':
                    pasteElement();
                    break;
                case 'copy-style':
                    copyStyle();
                    break;
                case 'paste-style':
                    pasteStyle();
                    break;
                case 'block-reveal':
                    if (ctx.element && ctx.element.id) openBlockRevealModal(ctx.element.id, ctx.element.type);
                    break;
                case 'toggle-push-bottom':
                    if (ctx.element && ctx.element.id) toggleBlockLayoutFlag(ctx.element.id, 'push_bottom', 'Push to bottom');
                    break;
                case 'paste-style-screen':
                    if (ctx && ctx.element && ctx.element.id && ctx.element.type) {
                        applyStyleToAllSameType(ctx.element.id, ctx.element.type, 'screen');
                    }
                    break;
                case 'paste-style-all':
                    if (ctx && ctx.element && ctx.element.id && ctx.element.type) {
                        applyStyleToAllSameType(ctx.element.id, ctx.element.type, 'page');
                    }
                    break;
                case 'reset-style':
                    if (selectedElementId && selectedElementType) {
                        
                        enqueueSave(selectedElementId, {}, function(ok) {
                            if (ok) { refreshPreview(); openSettings(selectedElementId, selectedElementType); }
                        });
                    }
                    break;
                case 'save-template':
                    saveAsTemplate();
                    break;
                case 'insert-from-library':

                    
                    var $libTab = $('.impulse-panel-tab[data-tab="templates"]');
                    if ($libTab.length && !$libTab.hasClass('active')) $libTab.trigger('click');
                    setTimeout(function() {
                        var $tplSub = $('.impulse-library-subtab[data-subtab="templates"]');
                        if ($tplSub.length && !$tplSub.hasClass('active')) $tplSub.trigger('click');
                        var $libPanel = $('.impulse-templates-panel, .impulse-library-panel').first();
                        if ($libPanel.length && $libPanel[0].scrollIntoView) {
                            $libPanel[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }
                    }, 80);
                    break;
                case 'save-default':
                    if (selectedElementId && selectedElementType) {
                        var _sdSettings = $('.impulse-panel-right').data('existing-settings') || {};
                        localStorage.setItem('impulse_default_' + selectedElementType, JSON.stringify(_sdSettings));
                        window.showToast && window.showToast('Default saved for ' + selectedElementType);
                    }
                    break;
                case 'edit-with-instagent':
                    var _eiId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                    if (_eiId) showInstagentEditOverlay(_eiId);
                    break;
                case 'toggle-hide-mobile': {
                    ctxHide();
                    var _hmId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                    if (!_hmId) break;
                    
                    var _hmHide = !(ctx && ctx.element && ctx.element.hiddenMobile);
                    var _hmVal  = _hmHide ? 'off' : 'all';
                    
                    enqueueSave(_hmId, { visibility_mobile: _hmVal });
                    
                    postToIframe({ type: 'impulse-visibility-update', id: _hmId, device: 'mobile', hidden: _hmHide });
                    
                    if (selectedElementId == _hmId) {
                        var _hmEs = $('.impulse-panel-right').data('existing-settings') || {};
                        _hmEs.visibility_mobile = _hmVal;
                        $('.impulse-panel-right').data('existing-settings', _hmEs);
                        if ((currentDevice || 'desktop') === 'mobile') {
                            var $vg = $('.impulse-btn-group-visibility');
                            if ($vg.length) {
                                $vg.find('button').removeClass('active');
                                $vg.find('button[data-value="' + _hmVal + '"]').addClass('active');
                                $vg.find('input[type="hidden"]').attr('name', 'visibility_mobile').val(_hmVal);
                                $vg.closest('.impulse-setting-row').addClass('has-override');
                            }
                        }
                    }
                    window.showToast && window.showToast(_hmHide ? 'Hidden on mobile' : 'Shown on mobile');
                    break;
                }
                case 'structure':
                    
                    $('.impulse-panel-tab[data-tab="structure"]').trigger('click');
                    break;
                case 'duplicate':
                    if (ctx && ctx.inSlider) {
                        duplicateSlide(parseInt(ctx.inSlider.sliderId), ctx.inSlider.slideIndex);
                    } else {
                        var _dupId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                        if (_dupId) duplicateElement(_dupId);
                    }
                    break;
                case 'convert-to-kinetic':
                    var _cvId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                    if (_cvId) convertHeadingToKinetic(_cvId);
                    break;
                case 'wrap-section':
                case 'wrap-rows':
                case 'wrap-columns':
                case 'wrap-grid':
                    var _wrapId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                    var _wrapKind = action.replace('wrap-', ''); 
                    if (_wrapId) wrapElementsInContainer([_wrapId], _wrapKind);
                    break;
                case 'wrap-selection-section':
                case 'wrap-selection-rows':
                case 'wrap-selection-columns':
                case 'wrap-selection-grid':

                    var _wsSel = (window._impMultiSel && window._impMultiSel.length >= 2)
                               ? window._impMultiSel.slice()
                               : ((ctx && ctx.multiSel) ? ctx.multiSel : []);
                    if (_wsSel.length >= 2) wrapElementsInContainer(_wsSel, action.replace('wrap-selection-', ''));
                    break;
                case 'convert-grid-to-rows':
                    var _cvId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                    if (_cvId) convertGridToRows(_cvId);
                    break;
                case 'delete':

                    

                    

                    

                    

                    
                    var _delId = (ctx && ctx.element && ctx.element.id) ? ctx.element.id : selectedElementId;
                    if (_delId) deleteElement(_delId, true);
                    break;
                
                case 'dup-cell':
                case 'del-cell':
                case 'dup-row':
                case 'del-row':
                    if (ctx.cell) {
                        if (ctx.cell.gridType === 'grid') {

                            
                            if (action === 'dup-row') handleMasonryGridDupRow(ctx.cell.gridId, ctx.cell.cellIdx);
                        } else {
                            handleCellAction(action, ctx.cell.gridId, ctx.cell.row, ctx.cell.col);
                        }
                    }
                    break;
                case 'export-page':
                    (function() {
                        $.ajax({
                            url: Impulse.api + 'pages/' + Impulse.pageId + '/export',
                            method: 'GET',
                            headers: { 'X-WP-Nonce': Impulse.nonce },
                            success: function(data) {
                                var json = JSON.stringify(data, null, 2);
                                var blob = new Blob([json], { type: 'application/json' });
                                var a = document.createElement('a');
                                a.href = URL.createObjectURL(blob);
                                a.download = (data.page && data.page.slug ? data.page.slug : 'page-' + Impulse.pageId) + '.json';
                                a.click();
                                URL.revokeObjectURL(a.href);
                                window.showToast && window.showToast('Page exported');
                            },
                            error: function() {
                                window.showToast && window.showToast('Export failed');
                            }
                        });
                    })();
                    break;
                case 'import-page':
                    (function() {
                        var input = document.createElement('input');
                        input.type = 'file';
                        input.accept = '.json';
                        input.style.display = 'none';
                        input.onchange = function() {
                            var file = input.files[0];
                            if (!file) return;
                            var reader = new FileReader();
                            reader.onload = function(e) {
                                try {
                                    var data = JSON.parse(e.target.result);
                                } catch(err) {
                                    window.showToast && window.showToast('Invalid JSON file');
                                    return;
                                }
                                
                                var targetId = Impulse.pageId || 0;
                                var url = Impulse.api + 'pages/import';
                                if (targetId) url += '?page_id=' + targetId;
                                $.ajax({
                                    url: url,
                                    method: 'POST',
                                    headers: { 'X-WP-Nonce': Impulse.nonce },
                                    contentType: 'application/json',
                                    data: JSON.stringify(data),
                                    success: function(resp) {
                                        if (resp.success && resp.id) {
                                            window.showToast && window.showToast('Page imported');
                                            
                                            setTimeout(function() {
                                                window.location.href = (window.Impulse.adminBaseUrl + (window.Impulse.adminBaseUrl.indexOf('?') > -1 ? '&' : '?') + 'p=' + resp.id);
                                            }, 600);
                                        } else {
                                            window.showToast && window.showToast(resp.error || 'Import failed');
                                        }
                                    },
                                    error: function() {
                                        window.showToast && window.showToast('Import failed');
                                    }
                                });
                            };
                            reader.readAsText(file);
                        };
                        document.body.appendChild(input);
                        input.click();
                        document.body.removeChild(input);
                    })();
                    break;
            }
            
            ctxHide();
        });

        

        
        function handleMasonryGridDupRow(gridId, cellIdx) {
            $.ajax({
                url: Impulse.api + 'elements/' + gridId,
                method: 'GET',
                headers: { 'X-WP-Nonce': Impulse.nonce }
            }).done(function(row) {
                var s = (row && row.settings) || {};
                var cols = parseInt(s.columns) || 1;
                var rows = parseInt(s.rows) || 1;
                if (rows >= 8) { window.showToast && window.showToast('Max 8 rows', 'error'); return; }
                var srcRow = Math.floor(cellIdx / cols);
                $.ajax({
                    url: Impulse.api + 'elements/' + gridId + '/duplicate-row',
                    method: 'POST',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({ page_id: Impulse.pageId, row: srcRow, cellIdx: cellIdx })
                }).always(function() { refreshPreview(); });
            });
        }

        function handleCellAction(action, gridId, row, col) {
            var ctRows = null;
            
            if ($('.impulse-panel-right').data('element-id') == gridId) {
                var _es = $('.impulse-panel-right').data('existing-settings');
                if (_es && _es.rows) ctRows = typeof _es.rows === 'string' ? JSON.parse(_es.rows) : _es.rows;
            }
            
            if (!ctRows) {
                var _cc = cellGridSettingsCache[gridId];
                if (_cc && _cc.rows) ctRows = typeof _cc.rows === 'string' ? JSON.parse(_cc.rows) : _cc.rows;
            }
            
            if (!ctRows) {
                try {
                    var _xhr = $.ajax({ url: Impulse.api + 'elements/' + gridId, method: 'GET', headers: { 'X-WP-Nonce': Impulse.nonce }, async: false });
                    if (_xhr.responseJSON && _xhr.responseJSON.settings) {
                        var _rs = _xhr.responseJSON.settings;
                        ctRows = typeof _rs.rows === 'string' ? JSON.parse(_rs.rows) : (_rs.rows || []);
                    }
                } catch(ex) {}
            }
            if (!ctRows || !ctRows.length) return;
            
            function ctSaveRows(gid, rows, cb) {
                if (!cellGridSettingsCache[gid]) cellGridSettingsCache[gid] = {};
                cellGridSettingsCache[gid].rows = rows;
                if ($('.impulse-panel-right').data('element-id') == gid) {
                    $('input[name="rows"]').val(JSON.stringify(rows));
                    var _ex = $('.impulse-panel-right').data('existing-settings') || {};
                    _ex.rows = rows;
                    $('.impulse-panel-right').data('existing-settings', _ex);
                }
                var saveSettings = $.extend({}, cellGridSettingsCache[gid]);
                saveSettings.rows = JSON.stringify(rows);
                $.ajax({ url: Impulse.api + 'elements/' + gid, method: 'PUT', headers: { 'X-WP-Nonce': Impulse.nonce }, contentType: 'application/json', data: JSON.stringify({ settings: saveSettings, page_id: Impulse.pageId }), success: function() { if (cb) cb(); } });
            }
            
            if (action === 'del-cell') {
                if (!ctRows[row] || ctRows[row].widths.length <= 1) return;
                ctRows[row].widths.splice(col, 1);
                ctRows[row].cells.splice(col, 1);
                var cw = 100 / ctRows[row].widths.length;
                ctRows[row].widths = ctRows[row].widths.map(function() { return Math.round(cw * 100) / 100; });
                ctSaveRows(gridId, ctRows, function() { refreshPreview(); });
            } else if (action === 'del-row') {
                if (ctRows.length <= 1) return;
                ctRows.splice(row, 1);
                ctSaveRows(gridId, ctRows, function() { refreshPreview(); });
            } else if (action === 'dup-cell') {
                if (!ctRows[row]) return;
                if (ctRows[row].widths.length >= 6) { window.showToast && window.showToast('Max 6 cells per row', 'error'); return; }
                var srcCell = ctRows[row].cells[col] || {};
                ctRows[row].widths.splice(col + 1, 0, ctRows[row].widths[col]);
                ctRows[row].cells.splice(col + 1, 0, JSON.parse(JSON.stringify(srcCell)));
                var dcw = 100 / ctRows[row].widths.length;
                ctRows[row].widths = ctRows[row].widths.map(function() { return Math.round(dcw * 100) / 100; });
                ctSaveRows(gridId, ctRows);
                $.ajax({ url: Impulse.api + 'elements/' + gridId + '/duplicate-cell', method: 'POST', headers: { 'X-WP-Nonce': Impulse.nonce }, contentType: 'application/json', data: JSON.stringify({ page_id: Impulse.pageId, row: row, col: col, new_col: col + 1, total_cols: ctRows[row].widths.length }), success: function() { refreshPreview(); }, error: function() { refreshPreview(); } });
            } else if (action === 'dup-row') {
                if (ctRows.length >= 6) { window.showToast && window.showToast('Max 6 rows', 'error'); return; }
                ctRows.splice(row + 1, 0, JSON.parse(JSON.stringify(ctRows[row])));
                ctSaveRows(gridId, ctRows);
                $.ajax({ url: Impulse.api + 'elements/' + gridId + '/duplicate-row', method: 'POST', headers: { 'X-WP-Nonce': Impulse.nonce }, contentType: 'application/json', data: JSON.stringify({ page_id: Impulse.pageId, row: row, new_row: row + 1, total_rows: ctRows.length }), success: function() { refreshPreview(); }, error: function() { refreshPreview(); } });
            }
        }

        
        
        $('.impulse-search').on('input', function() {
            var query = $(this).val().toLowerCase().trim();
            
            if (!query) {
                
                $('.impulse-block').show();
                $('.impulse-block-category').show();
                return;
            }

            $('.impulse-block').each(function() {
                var name = $(this).find('span').text().toLowerCase();
                var type = $(this).data('element').toLowerCase();
                var matches = name.indexOf(query) !== -1 || type.indexOf(query) !== -1;
                $(this).toggle(matches);
            });

            $('.impulse-block-category').each(function() {
                var hasVisible = $(this).find('.impulse-block:visible').length > 0;
                $(this).toggle(hasVisible);
            });
        });

        

        

        

        $('.impulse-global-tabs button').on('click', function() {
            var tab = $(this).data('gtab');
            $('.impulse-global-tabs button').removeClass('active');
            $(this).addClass('active');
            $('.impulse-global-pane').removeClass('active');
            $('.impulse-global-pane[data-gpane="' + tab + '"]').addClass('active');
        });

        $('#impulse-global-styles input[type="range"]').on('input', function() {
            impulseSliderTrack(this);
            var val = $(this).val();
            var unit = $(this).attr('name').includes('size') || $(this).attr('name').includes('padding') || $(this).attr('name').includes('radius') || $(this).attr('name').includes('gap') || $(this).attr('name').includes('width') ? 'px' : '';
            $(this).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(val + unit);
        });

        $('#impulse-save-global-styles').on('click', function() {
            var styles = {};
            $('#impulse-global-styles').find('input, select').each(function() {
                var name = $(this).attr('name');
                if (name) styles[name] = $(this).val();
            });

            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId,
                method: 'PUT',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({ settings: { global_styles: styles } }),
                success: function() {
                    window.showToast('Global styles saved');
                    $('#impulse-global-styles').hide();
                    refreshPreview();
                }
            });
        });

        
        
        function insertTemplateChildren(children, parentId) {
            if (!children || !children.length) {
                refreshPreview();
                return;
            }
            var i = 0;
            function next() {
                if (i >= children.length) {
                    refreshPreview();
                    setTimeout(updateStructureTree, 300);
                    return;
                }
                insertTemplateElements(children[i], parentId, function() {
                    i++;
                    next();
                });
            }
            next();
        }

        function templateChildrenCallback(children) {
            if (!children || !children.length) return null;
            return function(newId) {
                insertTemplateChildren(children, newId);
            };
        }
        
        function insertTemplateElements(template, parentId, callback) {
            $.ajax({
                url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                method: 'POST',
                headers: { 'X-WP-Nonce': Impulse.nonce },
                contentType: 'application/json',
                data: JSON.stringify({
                    element_type: template.type,
                    settings: template.settings || {},
                    parent_id: parentId || 0
                }),
                success: function(response) {
                    var newId = response.id;
                    if (template.children && template.children.length) {
                        
                        var i = 0;
                        function insertNext() {
                            if (i >= template.children.length) {
                                if (callback) callback(newId);
                                return;
                            }
                            insertTemplateElements(template.children[i], newId, function() {
                                i++;
                                insertNext();
                            });
                        }
                        insertNext();
                    } else {
                        if (callback) callback(newId);
                    }
                },
                error: function() {
                    window.showToast('Failed to insert template element');
                    if (callback) callback(null);
                }
            });
        }

        
        var shapesCache = null;
        var shapesLoaded = false;
        
        var shapesCategoriesCache = [];
        
        function loadShapesLibrary() {
            if (shapesLoaded) return;
            shapesLoaded = true;
            
            var $grid = $('#impulse-library-shapes-grid');
            $grid.html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:#888;font-size:11px">Loading shapes...</div>');
            
            $.ajax({
                url: 'https://platform.instinctor.com/api/shapes',
                method: 'GET',
                dataType: 'json',
                timeout: 15000,
                success: function(data) {
                    shapesCache = data.shapes || [];
                    shapesCategoriesCache = data.categories || [];
                    renderShapes(shapesCache, shapesCategoriesCache);
                },
                error: function(xhr, status) {
                    $grid.html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:'+ImpC.dim+';font-size:11px">Could not load shapes.<br><button type="button" class="impulse-shapes-retry" style="margin-top:8px;padding:4px 12px;background:'+ImpC.surface2+';color:'+ImpC.white+';border:none;border-radius:4px;cursor:pointer;font-size:11px">Retry</button></div>');
                    shapesLoaded = false;
                }
            });
        }
        
        function renderShapes(shapes, categories) {
            var $grid = $('#impulse-library-shapes-grid');
            $grid.empty();
            
            if (!shapes.length) {
                $grid.html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:#888;font-size:11px">No shapes available.</div>');
                return;
            }

            var groups = {};
            shapes.forEach(function(s) {
                var cat = s.category || 'other';
                if (!groups[cat]) groups[cat] = [];
                groups[cat].push(s);
            });
            
            var catOrder = (categories || []).slice().sort(function(a,b) { return (a.sort_order||0) - (b.sort_order||0); }).map(function(c) { return c.slug; });
            Object.keys(groups).forEach(function(k) { if (catOrder.indexOf(k) === -1) catOrder.push(k); });
            
            function sCatLabel(slug) {
                for (var i = 0; i < (categories || []).length; i++) {
                    if (categories[i].slug === slug) return categories[i].label;
                }
                return slug.charAt(0).toUpperCase() + slug.slice(1).replace(/[-_]/g, ' ');
            }
            
            catOrder.forEach(function(catSlug) {
                if (catSlug === 'masks') return; 
                var catShapes = groups[catSlug];
                if (!catShapes || !catShapes.length) return;
                
                $grid.append('<div style="width:100%;flex-basis:100%;font-size:10px;font-weight:600;color:#888;text-transform:uppercase;letter-spacing:0.5px;padding:6px 4px 2px;border-bottom:1px solid '+ImpC.border+';margin-top:4px">' + sCatLabel(catSlug) + '</div>');
                
                catShapes.forEach(function(shape) {
                    var $item = $('<div class="impulse-block impulse-shape-item" draggable="true" data-shape-id="' + shape.id + '">');
                    var svgHtml = shape.svg || '';
                    var defColors = shape.default_colors || [];
                    
                    if (defColors.length > 0) {
                        defColors.forEach(function(c, i) {
                            var dc = i + 1;
                            svgHtml = svgHtml.replace(new RegExp('data-c="' + dc + '"', 'g'), 'data-c="' + dc + '" fill="' + c + '"');
                            svgHtml = svgHtml.replace(new RegExp('data-s="' + dc + '"', 'g'), 'data-s="' + dc + '" stroke="' + c + '"');
                        });
                        $item.append('<div class="impulse-block-icon"><svg viewBox="' + (shape.viewbox || '0 0 24 24') + '" width="32" height="32">' + svgHtml + '</svg></div>');
                    } else {
                        $item.append('<div class="impulse-block-icon"><svg viewBox="' + (shape.viewbox || '0 0 24 24') + '" width="32" height="32" fill="'+ImpC.muted+'" stroke="none">' + svgHtml + '</svg></div>');
                    }
                    
                    $item.data('shape-data', shape);
                    $grid.append($item);
                });
            });
        }

        $(document).on('click', '.impulse-shapes-retry', function() {
            shapesLoaded = false;
            loadShapesLibrary();
        });

        
        var imagesCache = [];
        var imagesLoaded = false;
        
        function loadImagesLibrary() {
            if (imagesLoaded) return;
            imagesLoaded = true;
            
            var $grid = $('#impulse-library-images-grid');
            $grid.html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:#888;font-size:11px">Loading images...</div>');
            
            $.ajax({
                url: 'https://platform.instinctor.com/api/graphics',
                method: 'GET',
                dataType: 'json',
                timeout: 15000,
                success: function(data) {
                    imagesCache = data.graphics || [];
                    imagesCategoriesCache = data.categories || [];
                    renderImages(imagesCache, imagesCategoriesCache);
                },
                error: function() {
                    $grid.html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:'+ImpC.dim+';font-size:11px">Could not load images.<br><button type="button" class="impulse-images-retry" style="margin-top:8px;padding:4px 12px;background:'+ImpC.surface2+';color:'+ImpC.white+';border:none;border-radius:4px;cursor:pointer;font-size:11px">Retry</button></div>');
                    imagesLoaded = false;
                }
            });
        }
        
        var imagesCategoriesCache = [];
        
        function renderImages(images, categories) {
            var $grid = $('#impulse-library-images-grid');
            $grid.empty();
            
            if (!images.length) {
                $grid.html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:#888;font-size:11px">No images available.</div>');
                return;
            }

            var groups = {};
            images.forEach(function(img) {
                var cat = img.category || 'other';
                if (!groups[cat]) groups[cat] = [];
                groups[cat].push(img);
            });

            var catOrder = (categories || []).slice().sort(function(a,b) { return (a.sort_order||0) - (b.sort_order||0); }).map(function(c) { return c.slug; });
            Object.keys(groups).forEach(function(k) { if (catOrder.indexOf(k) === -1) catOrder.push(k); });
            
            function catLabel(slug) {
                for (var i = 0; i < (categories || []).length; i++) {
                    if (categories[i].slug === slug) return categories[i].label;
                }
                return slug.charAt(0).toUpperCase() + slug.slice(1).replace(/[-_]/g, ' ');
            }
            
            catOrder.forEach(function(catSlug) {
                var catImages = groups[catSlug];
                if (!catImages || !catImages.length) return;

                $grid.append('<div style="width:100%;flex-basis:100%;font-size:10px;font-weight:600;color:#888;text-transform:uppercase;letter-spacing:0.5px;padding:6px 4px 2px;border-bottom:1px solid '+ImpC.border+';margin-top:4px">' + catLabel(catSlug) + '</div>');
                
                catImages.forEach(function(img) {
                    var thumbUrl = img.thumbnail_url || img.image_url;
                    var $item = $('<div class="impulse-image-item" draggable="true" data-graphic-id="' + img.id + '">');
                    $item.append('<img src="' + thumbUrl + '" alt="' + (img.name || '') + '" loading="lazy">');
                    $item.data('graphic-data', img);
                    $grid.append($item);
                });
            });
        }

        $(document).on('click', '.impulse-images-retry', function() {
            imagesLoaded = false;
            loadImagesLibrary();
        });

        var mediaLibLoaded = false;
        var mediaLibLoading = false;
        var mediaLibPage = 1;
        var mediaLibHasMore = true;
        var mediaLibImages = {};
        var mediaLibFilter = ''; 
        var mediaLib3dDone = false; 

        

        function _mlibSyncTabs() {
            $('.impulse-medialib-filter').each(function() {
                var on = (($(this).data('mfilter') === '3d') === (mediaLibFilter === '3d'));
                $(this).css(on
                    ? { background: '#1d2327', color: '#fff', borderColor: '#1d2327' }
                    : { background: '#fff', color: '#555', borderColor: '#e0e0e0' });
            });
        }

        function loadMediaLibrary(reset) {
            if (mediaLibLoading) return;
            _mlibSyncTabs();
            if (reset) {
                mediaLibPage = 1;
                mediaLibHasMore = true;
                mediaLibImages = {};
                mediaLib3dDone = false;
                $('#impulse-library-media-grid').empty();
            }
            if (!mediaLibHasMore) return;

            mediaLibLoading = true;
            if (mediaLibPage === 1) {
                $('#impulse-library-media-grid').html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:#888;font-size:11px">Loading...</div>');
            }

            $.post(ajaxurl, {
                action: 'instinctor_imglib_get',
                nonce: window.Impulse.adminNonce,
                page: mediaLibPage,
                filter: mediaLibFilter
            }, function(r) {
                mediaLibLoading = false;
                if (!r.success) return;
                var d = r.data;
                mediaLibHasMore = d.page < d.pages;
                mediaLibPage++;

                $('#media-lib-count').text(d.total > 0 ? d.total + ' images' : '');

                if (d.images.length === 0 && d.page === 1 && mediaLibFilter !== '3d') {
                    $('#impulse-library-media-grid').html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:#888;font-size:11px">No images yet</div>');
                    return;
                }

                var $grid = $('#impulse-library-media-grid');
                if (mediaLibPage === 2) $grid.empty(); 

                d.images.forEach(function(img) {
                    mediaLibImages[img.id] = img;
                    var $item = $('<div class="impulse-media-item" draggable="true" data-media-id="' + img.id + '">');
                    $item.append('<img src="' + (img.thumb || img.url) + '" loading="lazy" alt="' + escapeHtml(img.title || img.filename || '') + '">');
                    $item.data('media-data', img);
                    $grid.append($item);
                });

                mediaLibLoaded = true;
                if (typeof _libPickHighlightCurrent === 'function') _libPickHighlightCurrent();
                if (mediaLibFilter === '3d' && !mediaLib3dDone) { mediaLib3dDone = true; _loadPlatform3dInto($('#impulse-library-media-grid')); }
            }).fail(function() {
                mediaLibLoading = false;
                $('#impulse-library-media-grid').html('<div style="grid-column:1/-1;text-align:center;padding:20px 0;color:'+ImpC.dim+';font-size:11px">Could not load.<br><button type="button" class="media-lib-retry impulse-btn-sm" style="margin-top:6px">Retry</button></div>');
            });
        }

        $(document).on('click', '.media-lib-retry', function() {
            mediaLibLoaded = false;
            loadMediaLibrary(true);
        });

        

        
        $(document).on('click', '.impulse-medialib-filter', function() {
            var f = ($(this).data('mfilter') === '3d') ? '3d' : '';
            if (f === mediaLibFilter && mediaLibLoaded) { _mlibSyncTabs(); return; }
            mediaLibFilter = f;
            loadMediaLibrary(true);
        });

        $(document).on('change', '#media-lib-upload-input', function() {
            var files = this.files;
            if (!files || !files.length) return;
            var $lbl = $(this).closest('label');
            $lbl.css('opacity', '0.5').prop('disabled', true);
            var remaining = files.length;
            Array.from(files).forEach(function(file) {
                var fd = new FormData();
                fd.append('action', 'instinctor_imglib_upload');
                fd.append('nonce', window.Impulse.adminNonce);
                fd.append('image', file);
                $.ajax({
                    url: ajaxurl, type: 'POST', data: fd, processData: false, contentType: false,
                    success: function(r) {
                        remaining--;
                        if (remaining === 0) $lbl.css('opacity', '1').prop('disabled', false);
                        if (!r.success) return;
                        var img = r.data;

                        

                        

                        

                        if (mediaLibPick && !(mediaLibPick.opts && mediaLibPick.opts.multiple)) {
                            var _cb = mediaLibPick.callback, _opts = mediaLibPick.opts || {};
                            var _sel = _libPickShape(img, _opts);
                            exitLibraryPick();
                            if (typeof _cb === 'function') _cb(_sel);
                            return;
                        }
                        mediaLibImages[img.id] = img;
                        var $item = $('<div class="impulse-media-item" draggable="true" data-media-id="' + img.id + '">');
                        $item.append('<img src="' + (img.thumb || img.url) + '" alt="' + escapeHtml(img.filename || '') + '">');
                        $item.data('media-data', img);
                        var $g = $('#impulse-library-media-grid');

                        

                        $g.children(':not(.impulse-media-item)').remove();
                        $g.prepend($item);
                        var total = parseInt($('#media-lib-count').text()) || 0;
                        $('#media-lib-count').text((total + 1) + ' images');
                    },
                    error: function() {
                        remaining--;
                        if (remaining === 0) $lbl.css('opacity', '1').prop('disabled', false);
                    }
                });
            });
            this.value = '';
        });

        $(document).on('scroll', '.impulse-panel-left .impulse-scroll, .impulse-panel-left', function() {
            if (!$('.impulse-library-media').is(':visible')) return;
            if (this.scrollTop + this.clientHeight >= this.scrollHeight - 120) loadMediaLibrary(false);
        });

        var mediaHoverTimeout = null;
        $(document).on('mouseenter', '.impulse-media-item', function(e) {
            var $item = $(this);
            var ev = e;
            mediaHoverTimeout = setTimeout(function() {
                var $hoverPreview = $('#impulse-hover-preview');
                if (!$hoverPreview.length) return;
                var img = $item.data('media-data');
                if (!img) return;
                var thumbUrl = img.thumb || img.url;
                var filename = img.filename || img.title || '';

                $hoverPreview.removeClass('preview-graphic').addClass('preview-media');
                
                $hoverPreview.find('.preview-content').html(
                    '<img src="' + thumbUrl + '" style="width:100%;height:auto;display:block">' +
                    '<div class="preview-label">' + escapeHtml(filename) + '</div>'
                );

                var actions = '<div class="impulse-media-hover-actions">' +
                    '<button type="button" class="impulse-btn-sm media-hover-copy" data-url="' + img.url + '" style="flex:1">Copy URL</button>' +
                    '<button type="button" class="impulse-btn-sm media-hover-delete" data-id="' + img.id + '" style="color:#888">Delete</button>' +
                    '</div>';
                
                if (!$hoverPreview.find('.impulse-media-hover-actions').length) {
                    $hoverPreview.append(actions);
                } else {
                    $hoverPreview.find('.impulse-media-hover-actions').replaceWith(actions);
                }

                var panelEl = $item.closest('.impulse-panel-left')[0];
                var left = panelEl ? panelEl.getBoundingClientRect().right + 8 : ev.clientX + 20;
                var top = ev.clientY - 60;
                var wh = $(window).height();
                var ph = 220;
                if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                $hoverPreview.css({ top: top, left: left, display: 'block' });
            }, 300);
        });

        $(document).on('mousemove', '.impulse-media-item', function(e) {
            if ($hoverPreview.is(':visible') && $hoverPreview.hasClass('preview-media')) {
                var top = e.clientY - 60;
                var wh = $(window).height();
                var ph = $hoverPreview.outerHeight() || 220;
                if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                $hoverPreview.css('top', top);
            }
        });

        $(document).on('mouseleave', '.impulse-media-item', function() {
            clearTimeout(mediaHoverTimeout);
            
        });

        $(document).on('mouseenter', '#impulse-hover-preview', function() {
            clearTimeout(mediaHoverTimeout);
        });
        $(document).on('mouseleave', '#impulse-hover-preview', function() {
            if ($(this).hasClass('preview-media')) {
                $(this).removeClass('preview-media').hide();
            }
        });

        $(document).on('click', '.media-hover-copy', function(e) {
            e.stopPropagation();
            var url = $(this).data('url');
            if (navigator.clipboard) {
                navigator.clipboard.writeText(url);
                var $btn = $(this);
                $btn.text('Copied!');
                setTimeout(function() { $btn.text('Copy URL'); }, 1500);
            }
        });

        $(document).on('click', '.media-hover-delete', function(e) {
            e.stopPropagation();
            var id = $(this).data('id');
            $hoverPreview.removeClass('preview-media').hide();
            $.post(ajaxurl, { action: 'instinctor_imglib_delete', nonce: window.Impulse.adminNonce, id: id }, function(r) {
                if (r.success) {
                    $('[data-media-id="' + id + '"]').remove();
                    delete mediaLibImages[id];
                    if (typeof showImpulseToast === 'function') showImpulseToast('Image deleted');
                }
            });
        });

        

        

        var mediaLibPick = null;
        function _libPickShape(img, opts) {
            return {
                id: img.id, url: img.url, alt: img.alt || '',
                focal_point: (opts && opts.currentFocalPoint) || img.focal || '50% 50%',
                width: img.width, height: img.height,
                depthUrl: img.depth_url || null,
                sizes: { thumbnail: { url: img.thumb || img.url }, full: { url: img.url } }
            };
        }

        
        function _loadPlatform3dInto($grid) {
            $.ajax({ url: 'https://platform.instinctor.com/api/graphics', method: 'GET', data: { category: '3d' }, dataType: 'json', timeout: 15000 })
            .done(function(platData) {
                var images = ((platData && platData.graphics) || []).filter(function(g) {
                    var file = (g.image_url || '').split('/').pop().replace(/\.[^.]+$/, '');
                    return !/^\d+a$/.test(file); 
                });
                if (!images.length) return;

                
                
                if ($grid.find('.impulse-media-item').length) {
                    $grid.append('<div style="grid-column:1/-1;font-size:10px;font-weight:600;color:#888;text-transform:uppercase;letter-spacing:0.5px;padding:6px 4px 2px;margin-top:4px;border-bottom:1px solid ' + ImpC.border + '">Platform 3D</div>');
                }
                images.forEach(function(img) {
                    var depthUrl = (img.image_url || '').replace(/(\.[^\/\.]+)$/, 'a.png');
                    var locked = false; 
                    var data = { id: 'p_' + img.id, url: img.image_url, thumb: img.thumbnail_url || img.image_url, alt: img.name || '', width: img.width || 0, height: img.height || 0, depth_url: depthUrl };
                    var $item = $('<div class="impulse-media-item' + (locked ? ' impulse-pro-locked' : '') + '" data-media-id="p_' + img.id + '"' + (locked ? ' data-pro-locked="1" data-pro-label="3D image"' : '') + '>');
                    $item.append('<img src="' + data.thumb + '" loading="lazy" alt="' + escapeHtml(data.alt) + '">');
                    $item.data('media-data', data);
                    $grid.append($item);
                });
            });
        }
        function _libPickHighlightCurrent() {
            if (!mediaLibPick || !mediaLibPick.opts || !mediaLibPick.opts.currentId) return;
            var el = document.querySelector('.impulse-media-item[data-media-id="' + mediaLibPick.opts.currentId + '"]');
            if (el) { el.style.outline = '2px solid ' + ImpC.text; el.style.outlineOffset = '-2px'; el.scrollIntoView({ block: 'nearest' }); }
        }
        function exitLibraryPick() {

            var _returnTab = (mediaLibPick && mediaLibPick.returnTab) || null;
            mediaLibPick = null;
            $('.impulse-library-media').removeClass('impulse-lib-pick-mode impulse-lib-pick-multi');
            $('.impulse-media-item').each(function(){ this.style.outline = ''; this.style.outlineOffset = ''; });
            $('#impulse-lib-pick-banner').remove();
            $('#media-lib-upload-input').closest('label').show();
            if (mediaLibFilter !== '') { mediaLibFilter = ''; loadMediaLibrary(true); } 

            

            if (_returnTab && _returnTab !== 'templates') {
                setTimeout(function(){ $('.impulse-panel-tab[data-tab="' + _returnTab + '"]').trigger('click'); }, 0);
            }
        }
        window.exitLibraryPick = exitLibraryPick;
        window.openLibraryPick = function(opts, callback) {
            opts = opts || {};

            
            var _fromTab = $('.impulse-panel-tab.active').data('tab');
            mediaLibPick = { opts: opts, callback: callback, selected: [], returnTab: (_fromTab && _fromTab !== 'templates') ? _fromTab : null };

            

            mediaLibFilter = (opts.platformCategory === '3d' || opts.depth) ? '3d' : '';
            
            $('.impulse-panel-tab[data-tab="templates"]').trigger('click');
            $('.impulse-library-subtab[data-subtab="media"]').trigger('click');
            loadMediaLibrary(true);
            var label = opts.label || 'Select Image';
            var multi = !!opts.multiple;
            $('#impulse-lib-pick-banner').remove();
            var right = (multi
                ? '<span id="impulse-lib-pick-count" style="font-size:11px;opacity:0.85">0 selected</span>'
                  + '<button type="button" id="impulse-lib-pick-add" disabled style="height:22px;padding:0 9px;font-size:11px;border:none;background:' + ImpC.surface2 + ';color:' + ImpC.muted + ';border-radius:3px;cursor:not-allowed">Add</button>'
                : '')
                + '<button type="button" id="impulse-lib-pick-cancel" style="height:22px;padding:0 8px;font-size:11px;border:1px solid ' + ImpC.surface2 + ';background:transparent;color:' + ImpC.surface2 + ';border-radius:3px;cursor:pointer">Cancel</button>';
            var banner = '<div id="impulse-lib-pick-banner" style="display:flex;align-items:center;justify-content:space-between;gap:8px;padding:7px 9px;margin-bottom:8px;background:' + ImpC.text + ';color:' + ImpC.surface2 + ';border-radius:3px;font-size:11px;font-weight:600">'
                + '<span>' + escapeHtml(label) + '</span>'
                + '<div style="display:flex;align-items:center;gap:6px">' + right + '</div>'
                + '</div>';
            var $panel = $('.impulse-library-media').addClass('impulse-lib-pick-mode');
            if (multi) $panel.addClass('impulse-lib-pick-multi');
            $panel.prepend(banner);
            
            $('#media-lib-upload-input').closest('label')[opts.noUpload ? 'hide' : 'show']();
        };
        function _libPickUpdateBar() {
            if (!mediaLibPick) return;
            var n = mediaLibPick.selected.length;
            $('#impulse-lib-pick-count').text(n + ' selected');
            $('#impulse-lib-pick-add').prop('disabled', n === 0).css({
                color: n ? ImpC.light : ImpC.muted,
                cursor: n ? 'pointer' : 'not-allowed'
            }).text(n ? ('Add ' + n) : 'Add');
        }
        $(document).on('click', '#impulse-lib-pick-cancel', function(e) {
            e.stopPropagation();
            exitLibraryPick();
        });
        $(document).on('click', '#impulse-lib-pick-add', function(e) {
            e.stopPropagation();
            if (!mediaLibPick || !mediaLibPick.selected.length) return;
            var cb = mediaLibPick.callback, opts = mediaLibPick.opts || {};
            var arr = mediaLibPick.selected.map(function(img){ return _libPickShape(img, opts); });
            exitLibraryPick();
            if (typeof cb === 'function') cb(arr);
        });
        $(document).on('click', '.impulse-media-item', function(e) {
            if (!mediaLibPick) return; 
            e.preventDefault();
            e.stopPropagation();
            var img = $(this).data('media-data');
            if (!img) return;
            if ($(this).hasClass('impulse-pro-locked')) { if (typeof showImpulseToast === 'function') showImpulseToast('This 3D image needs Pro.'); return; }
            var opts = mediaLibPick.opts || {};
            if (opts.multiple) {
                var idx = mediaLibPick.selected.indexOf(img);
                if (idx >= 0) { mediaLibPick.selected.splice(idx, 1); this.style.outline = ''; this.style.outlineOffset = ''; }
                else { mediaLibPick.selected.push(img); this.style.outline = '2px solid ' + ImpC.text; this.style.outlineOffset = '-2px'; }
                _libPickUpdateBar();
                return;
            }
            var cb = mediaLibPick.callback;
            var sel = _libPickShape(img, opts);
            exitLibraryPick();
            if (typeof cb === 'function') cb(sel);
        });

        $(document).on('click', '.impulse-graphics-subtab', function() {
            var subtab = $(this).data('gfx-subtab');
            $('.impulse-graphics-subtab').removeClass('active').css({ background: ''+ImpC.panel+'', color: ''+ImpC.muted+'' });
            $(this).addClass('active').css({ background: ''+ImpC.text+'', color: ''+ImpC.surface2+'' });
            $('.impulse-gfx-content').removeClass('active').hide();
            $('.impulse-gfx-' + subtab).addClass('active').show();
            if (subtab === 'shapes') loadShapesLibrary();
            if (subtab === 'images') loadImagesLibrary();
        });

        
        var sectionsCache = null;
        var sectionsLoaded = false;
        
        function loadRemoteSections() {
            if (sectionsLoaded) return;
            sectionsLoaded = true;
            
            var $grid = $('#impulse-remote-sections-grid');
            $grid.html('<div style="text-align:center;padding:20px 0;color:#888;font-size:11px">Loading sections...</div>');
            
            $.ajax({
                url: 'https://platform.instinctor.com/api/sections',
                method: 'GET',
                dataType: 'json',
                timeout: 15000,
                success: function(data) {
                    sectionsCache = data.sections || [];
                    renderRemoteSections(sectionsCache);
                },
                error: function() {
                    $grid.html('<div style="text-align:center;padding:20px 0;color:#888;font-size:11px">Could not load sections.<br><button type="button" class="impulse-sections-retry" style="margin-top:8px;padding:4px 12px;background:'+ImpC.surface2+';color:'+ImpC.white+';border:none;border-radius:4px;cursor:pointer;font-size:11px">Retry</button></div>');
                    sectionsLoaded = false;
                }
            });
        }
        
        function renderRemoteSections(sections) {
            var $grid = $('#impulse-remote-sections-grid');
            $grid.empty();
            
            if (!sections.length) {
                $grid.html('<div style="text-align:center;padding:20px 0;color:#888;font-size:11px">No sections available.</div>');
                return;
            }

            var categories = {};
            sections.forEach(function(s) {
                var cat = s.category || 'General';
                if (!categories[cat]) categories[cat] = [];
                categories[cat].push(s);
            });
            
            Object.keys(categories).forEach(function(cat) {
                if (Object.keys(categories).length > 1) {
                    $grid.append('<div class="impulse-section-category-label">' + cat + '</div>');
                }
                categories[cat].forEach(function(section) {
                    var $item = $('<div class="impulse-section-template impulse-remote-section" draggable="true" data-section-id="' + section.id + '">');
                    $item.append('<div class="impulse-template-thumb">' + (section.preview || '') + '</div>');
                    $item.append('<span>' + (section.name || section.id) + '</span>');
                    $item.data('section-tree', section.tree);
                    $grid.append($item);
                });
            });
        }

        $(document).on('click', '.impulse-sections-retry', function() {
            sectionsLoaded = false;
            loadRemoteSections();
        });

        $(document).on('click', '.impulse-remote-section', function(e) {
            var tree = $(this).data('section-tree');
            if (!tree || !Impulse.pageId) return;

            var containerTypes = ['section',  'rows', 'columns', 'slider', 'modal'];
            var rootOnlyTypes = ['modal'];
            var parentId = 0;
            var siblingId = null;
            var sType = tree.type || 'section';
            
            if (selectedElementId && selectedElementType) {
                if (containerTypes.indexOf(selectedElementType) !== -1) {
                    if (rootOnlyTypes.indexOf(sType) !== -1) {
                        
                        siblingId = selectedElementId;
                    } else {
                        parentId = selectedElementId;
                    }
                } else {
                    siblingId = selectedElementId;
                }
            }
            
            if (siblingId) {
                
                $.ajax({
                    url: Impulse.api + 'pages/' + Impulse.pageId + '/elements',
                    method: 'POST',
                    headers: { 'X-WP-Nonce': Impulse.nonce },
                    contentType: 'application/json',
                    data: JSON.stringify({
                        element_type: tree.type || 'section',
                        settings: tree.settings || {},
                        sibling_id: siblingId,
                        insert_position: 'after'
                    }),
                    success: function(resp) {
                        if (resp.id && tree.children && tree.children.length) {
                            insertTemplateChildren(tree.children, resp.id);
                        } else {
                            refreshPreview();
                        }
                        window.showToast('Section inserted');
                        setTimeout(updateStructureTree, 500);
                    },
                    error: function() { window.showToast('Failed to insert section'); }
                });
            } else {
                insertTemplateElements(tree, parentId, function() {
                    window.showToast('Section inserted');
                    refreshPreview();
                    setTimeout(updateStructureTree, 300);
                });
            }
        });

        $(document).on('dragstart', '.impulse-remote-section', function(e) {
            var tree = $(this).data('section-tree');
            if (!tree) return;
            var payload = JSON.stringify({
                type: 'user-template',
                templateId: $(this).data('section-id'),
                elementType: tree.type || 'section',
                settings: tree.settings || {},
                children: tree.children || []
            });
            draggedElement = payload;
            draggedTemplate = null;
            e.originalEvent.dataTransfer.setData('text/plain', payload);
            e.originalEvent.dataTransfer.effectAllowed = 'copy';
            $(this).addClass('dragging');
            $('.impulse-canvas').addClass('drag-active');
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ 
                    type: 'impulse-drag-start',
                    element: payload,
                    template: null
                }, '*');
            }
        });
        
        $(document).on('dragend', '.impulse-remote-section', function(e) {
            $(this).removeClass('dragging');
            $('.impulse-canvas').removeClass('drag-over drag-active');
            
            var element = draggedElement;
            setTimeout(function() {
                if (!window._dropHandled && element && lastDragPosition.fromIframe) {
                    var iframe = document.getElementById('impulse-iframe');
                    if (iframe && iframe.contentWindow) {
                        iframe.contentWindow.postMessage({ 
                            type: 'impulse-find-drop-at-position',
                            element: element,
                            template: null,
                            x: lastDragPosition.x,
                            y: lastDragPosition.y
                        }, '*');
                    }
                }
                window._dropHandled = false;
                var iframe = document.getElementById('impulse-iframe');
                if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({ type: 'impulse-drag-end' }, '*');
                }
            }, 100);
            
            draggedElement = null;
            draggedTemplate = null;
            lastDragPosition = { x: 0, y: 0, fromIframe: false };
        });

        $(document).on('click', '.impulse-panel-tab[data-tab="templates"]', function() {
            loadShapesLibrary();
            
            if (!selectedElementId) {
                showPageSettings();
            }
        });

        $(document).on('click', '.impulse-library-subtab', function() {
            var subtab = $(this).data('subtab');
            $('.impulse-library-subtab').removeClass('active');
            $(this).addClass('active');
            $('.impulse-library-content').removeClass('active').hide();
            $('.impulse-library-' + subtab).addClass('active').show();
            if (subtab === 'graphics') loadShapesLibrary();
            if (subtab === 'templates') { loadUserTemplates(function() { renderUserTemplates(); }); }
            if (subtab === 'media' && !mediaLibLoaded) loadMediaLibrary(true);
        });

        $(document).on('dragstart', '.impulse-shape-item', function(e) {
            var shape = $(this).data('shape-data');
            if (!shape) return;
            draggedElement = 'shape:' + shape.id;
            e.originalEvent.dataTransfer.setData('text/plain', 'shape:' + shape.id);
            e.originalEvent.dataTransfer.effectAllowed = 'copy';
            window._draggedShapeData = shape;
            isDragActive = true; 
            $('.impulse-canvas').addClass('drag-active');
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-drag-start', element: 'shape:' + shape.id }, '*');
            }
        });
        
        $(document).on('dragend', '.impulse-shape-item', function() {
            $('.impulse-canvas').removeClass('drag-over drag-active');
            isDragActive = false;
            if (pendingRefresh) { pendingRefresh = false; refreshPreview(); }

            draggedElement = null;
        });

        $(document).on('dragstart', '.impulse-media-item', function(e) {
            var media = $(this).data('media-data');
            if (!media) return;
            draggedElement = 'media:' + media.id;
            e.originalEvent.dataTransfer.setData('text/plain', 'media:' + media.id);
            e.originalEvent.dataTransfer.effectAllowed = 'copy';
            window._draggedMediaData = media;
            isDragActive = true;
            $('.impulse-canvas').addClass('drag-active');
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-drag-start', element: 'media:' + media.id }, '*');
            }
        });

        $(document).on('dragend', '.impulse-media-item', function() {
            $('.impulse-canvas').removeClass('drag-over drag-active');
            isDragActive = false;
            if (pendingRefresh) { pendingRefresh = false; refreshPreview(); }
            draggedElement = null;
        });

        

        

        
        var $hoverPreview = $('<div class="impulse-hover-preview" id="impulse-hover-preview"><div class="preview-content"></div><div class="preview-label"></div></div>');
        $('body').append($hoverPreview);
        var hoverTimeout = null;
        
        function showTemplatePreview($item, e) {
            
            var $thumb = $item.find('.impulse-template-thumb, .template-preview').first();
            if (!$thumb.length || !$.trim($thumb.html())) return;

            var name = $item.find('span, .template-name').first().text() || '';

            

            var tplId  = $item.attr('data-template-id');
            var tplSrc = $item.attr('data-source') || 'local';
            var pool   = tplSrc === 'platform' ? getPlatformSections() : getUserTemplates();
            var tpl    = tplId ? pool.find(function(t) { return String(t.id) === String(tplId); }) : null;
            if (tpl && tpl.html_preview) {
                var $slot = $hoverPreview.find('.preview-content');

                
                
                $slot[0].style.cssText = 'position:relative;width:100%;overflow:hidden;border-radius:4px;background:transparent';
                $slot.empty();

                
                mountLibraryPreviewIframe($slot[0], tpl.html_preview, { fallbackWidth: 260, animated: true });
                setTimeout(function() {
                    if ($hoverPreview.is(':visible') && $slot[0].clientWidth > 0) {
                        mountLibraryPreviewIframe($slot[0], tpl.html_preview, { animated: true });
                    }
                }, 30);
            } else {
                $hoverPreview.find('.preview-content').html($thumb.html());
            }
            $hoverPreview.find('.preview-label').text(name);
            $hoverPreview.removeClass('preview-graphic');

            var panelEl = $item.closest('.impulse-panel-left, .impulse-templates-panel, .impulse-blocks-panel')[0];
            var left, top;
            if (panelEl) {
                var rect = panelEl.getBoundingClientRect();
                left = rect.right + 8;
            } else {
                left = e.clientX + 20;
            }
            top = e.clientY - 80;

            var wh = $(window).height();
            var ww = $(window).width();
            if (top < 10) top = 10;
            if (left + 300 > ww) left = e.clientX - 300;
            
            $hoverPreview.css({ top: top, left: left, display: 'block' });
            
            var ph = $hoverPreview.outerHeight();
            if (top + ph > wh - 10) $hoverPreview.css('top', Math.max(10, wh - ph - 10));
        }
        
        $(document).on('mouseenter', '.impulse-section-template, .impulse-my-template-item', function(e) {
            var $item = $(this);
            var ev = e;
            hoverTimeout = setTimeout(function() {
                showTemplatePreview($item, ev);
            }, 300);
        });
        
        $(document).on('mousemove', '.impulse-section-template, .impulse-my-template-item', function(e) {
            
            if ($hoverPreview.is(':visible')) {
                var top = e.clientY - 80;
                var wh = $(window).height();
                var ph = $hoverPreview.outerHeight();
                if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                $hoverPreview.css('top', top);
            }
        });
        
        $(document).on('mouseleave', '.impulse-section-template, .impulse-my-template-item', function() {
            clearTimeout(hoverTimeout);
            $hoverPreview.hide();
        });

        $(document).on('dragstart', '.impulse-section-template, .impulse-my-template-item', function() {
            clearTimeout(hoverTimeout);
            $hoverPreview.hide();
        });

        

        
        
        var _hoverSafetyTick = false;
        var _mediaSafetyHide = null;
        $(document).on('mousemove', function(e) {
            if (_hoverSafetyTick) return;
            _hoverSafetyTick = true;
            requestAnimationFrame(function() { _hoverSafetyTick = false; });
            if (!$hoverPreview.is(':visible')) return;
            var t = e.target;
            if (!t || !t.closest) return;

            

            
            if (t.closest('.impulse-section-template, .impulse-my-template-item, .impulse-shape-item, .impulse-image-item, .impulse-media-item, #impulse-hover-preview')) {
                clearTimeout(_mediaSafetyHide);
                _mediaSafetyHide = null;
                return;
            }

            
            
            if ($hoverPreview.hasClass('preview-media')) {
                if (!_mediaSafetyHide) {
                    _mediaSafetyHide = setTimeout(function() {
                        _mediaSafetyHide = null;
                        if (!$hoverPreview.is(':hover')) {
                            $hoverPreview.hide().removeClass('preview-media');
                        }
                    }, 450);
                }
                return;
            }
            $hoverPreview.hide();
            clearTimeout(hoverTimeout);
        });

        $(document).on('mouseenter', '.impulse-shape-item', function(e) {
            var $item = $(this);
            var ev = e;
            hoverTimeout = setTimeout(function() {
                var shapeData = $item.data('shape-data');
                if (!shapeData) return;
                var svgHtml = shapeData.svg || '';
                var defColors = shapeData.default_colors || [];
                if (defColors.length > 0) {
                    defColors.forEach(function(c, i) {
                        var dc = i + 1;
                        svgHtml = svgHtml.replace(new RegExp('data-c="' + dc + '"', 'g'), 'data-c="' + dc + '" fill="' + c + '"');
                        svgHtml = svgHtml.replace(new RegExp('data-s="' + dc + '"', 'g'), 'data-s="' + dc + '" stroke="' + c + '"');
                    });
                } else {
                    svgHtml = '<g fill="'+ImpC.muted+'" stroke="none">' + svgHtml + '</g>';
                }
                $hoverPreview.find('.preview-content').html('<svg viewBox="' + (shapeData.viewbox || '0 0 24 24') + '" style="width:100%;height:auto;display:block">' + svgHtml + '</svg>');
                $hoverPreview.find('.preview-label').text(shapeData.name || '');
                $hoverPreview.addClass('preview-graphic');
                
                var panelEl = $item.closest('.impulse-panel-left')[0];
                var left = panelEl ? panelEl.getBoundingClientRect().right + 8 : ev.clientX + 20;
                var top = ev.clientY - 80;
                var wh = $(window).height();
                var ph = $hoverPreview.outerHeight() || 300; if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                if (left + 300 > $(window).width()) left = ev.clientX - 300;
                $hoverPreview.css({ top: top, left: left, display: 'block' });
            }, 300);
        });
        
        $(document).on('mousemove', '.impulse-shape-item', function(e) {
            if ($hoverPreview.is(':visible')) {
                var top = e.clientY - 80;
                var wh = $(window).height();
                var ph = $hoverPreview.outerHeight() || 300; if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                $hoverPreview.css('top', top);
            }
        });
        
        $(document).on('mouseleave', '.impulse-shape-item', function() {
            clearTimeout(hoverTimeout);
            $hoverPreview.hide();
        });
        
        $(document).on('dragstart', '.impulse-shape-item', function() {
            clearTimeout(hoverTimeout);
            $hoverPreview.hide();
        });

        $(document).on('mouseenter', '.impulse-image-item', function(e) {
            var $item = $(this);
            var ev = e;
            hoverTimeout = setTimeout(function() {
                var gfxData = $item.data('graphic-data');
                if (!gfxData) return;
                var imgUrl = gfxData.image_url || gfxData.thumbnail_url || '';
                if (!imgUrl) return;
                $hoverPreview.find('.preview-content').html('<img src="' + imgUrl + '" style="width:100%;height:auto;display:block;border-radius:4px">');
                $hoverPreview.find('.preview-label').text(gfxData.name || '');
                $hoverPreview.addClass('preview-graphic');
                
                var panelEl = $item.closest('.impulse-panel-left')[0];
                var left = panelEl ? panelEl.getBoundingClientRect().right + 8 : ev.clientX + 20;
                var top = ev.clientY - 80;
                var wh = $(window).height();
                var ph = $hoverPreview.outerHeight() || 300; if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                if (left + 300 > $(window).width()) left = ev.clientX - 300;
                $hoverPreview.css({ top: top, left: left, display: 'block' });
            }, 300);
        });
        
        $(document).on('mousemove', '.impulse-image-item', function(e) {
            if ($hoverPreview.is(':visible')) {
                var top = e.clientY - 80;
                var wh = $(window).height();
                var ph = $hoverPreview.outerHeight() || 300; if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
                if (top < 10) top = 10;
                $hoverPreview.css('top', top);
            }
        });
        
        $(document).on('mouseleave', '.impulse-image-item', function() {
            clearTimeout(hoverTimeout);
            $hoverPreview.hide();
        });
        
        $(document).on('dragstart', '.impulse-image-item', function() {
            clearTimeout(hoverTimeout);
            $hoverPreview.hide();
        });

        

        
        $(document).on('click', '.impulse-section-anim-layer-header', function(e) {

            if ($(e.target).closest('.impulse-toolbox-btn').length) return;
            var $content = $(this).siblings('.impulse-section-anim-layer-content');
            var $toggle  = $(this).find('.impulse-section-anim-layer-toggle');

            var willOpen = !$content.is(':visible');
            $content.stop(true, false).slideToggle(150);
            
            $toggle.css('transform', willOpen ? 'rotate(0deg)' : 'rotate(-90deg)');
        });

        

        
        $(document).on('contextmenu', '.impulse-section-anim-layer-header', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $layer = $(this).closest('.impulse-section-anim-layer');
            var idx    = parseInt($layer.attr('data-layer-index'), 10);
            var layers = _readAnimLayers();
            var layer  = layers[idx] || {};
            var visible = layer._visible !== false;
            var html = '';
            html += ctxItem('anim-layer-toggle-vis:' + idx, visible ? 'Hide layer' : 'Show layer');
            html += ctxItem('anim-layer-duplicate:' + idx, 'Duplicate');
            html += ctxDiv();
            html += ctxItem('anim-layer-delete:' + idx, 'Delete', '', 'danger');
            ctxShow($('#impulse-context-menu'), e.clientX, e.clientY, html);
        });

        $(document).on('click', '#impulse-context-menu .impulse-context-item', function(e) {
            var action = $(this).attr('data-action') || '';
            var m = action.match(/^anim-layer-(\w+(?:-\w+)*):(\d+)$/);
            if (!m) return; 
            var verb = m[1], idx = parseInt(m[2], 10);
            ctxHide();
            var layers = _readAnimLayers();
            var layer  = layers[idx];
            if (!layer) return;
            if (verb === 'toggle-vis') {
                layer._visible = (layer._visible === false); 
                $('#impulse-section-anim-layers-data').val(JSON.stringify(layers));

                

                $('.impulse-section-anim-layer[data-layer-index="' + idx + '"]')
                    .toggleClass('impulse-anim-layer-hidden', !layer._visible);
                animSaveAndUpdate();
                if (isPageSettingsMode()) refreshPreview();
            } else if (verb === 'duplicate') {
                var clone = JSON.parse(JSON.stringify(layer)); 
                layers.splice(idx + 1, 0, clone);
                $('#impulse-section-anim-layers-data').val(JSON.stringify(layers));
                animSaveAndUpdate();
                if (isPageSettingsMode()) refreshPreview();
            } else if (verb === 'delete') {
                $('.impulse-section-anim-layer[data-layer-index="' + idx + '"] .impulse-section-anim-layer-delete').trigger('click');
            }
        });

        function _readAnimLayers() {
            try { return JSON.parse($('#impulse-section-anim-layers-data').val() || '[]'); }
            catch (e) { return []; }
        }

        
        $(document).on('click', '.impulse-section-anim-layer-delete', function() {
            var $layer = $(this).closest('.impulse-section-anim-layer');
            if ($('.impulse-section-anim-layer').length <= 1) {
                window.showToast && window.showToast('Cannot delete the last layer.', 'error');
                return;
            }
            $layer.remove();
            $('.impulse-section-anim-layer').each(function(i) {
                $(this).attr('data-layer-index', i);
                $(this).find('.impulse-section-anim-layer-header span:eq(1)').text('Layer ' + (i + 1));
            });
            updateSectionAnimLayersData();

            

            
            animSaveAndUpdate();
        });

        $(document).on('click', '.impulse-add-section-anim-layer', function() {
            var $container = $('.impulse-section-anim-layers-container');
            var idx = $container.find('.impulse-section-anim-layer').length;
            if (idx >= 3) return; 

            

            
            var _existingHasLava = false;
            $container.find('.impulse-section-anim-layer-effect').each(function () {
                if (this.value === 'lava') { _existingHasLava = true; }
            });
            if (_existingHasLava) {
                if (typeof showToast === 'function') showToast('Lava covers the whole layer — extra layers would be invisible.', 'info');
                return;
            }

            
            
            var newLayer = {
                effect: '',
                opacity: 100,
                blend_mode: 'normal',
                settings: { origin_x: 50, origin_y: 50, color: '#888888' }
            };
            
            var html = '<div class="impulse-section-anim-layer" data-layer-index="' + idx + '" style="margin-bottom:6px">';
            html += '<div class="impulse-section-anim-layer-header" style="display:flex;align-items:center;justify-content:space-between;padding:6px 0;cursor:pointer;border-bottom:1px solid '+ImpC.border+'">';
            html += '<div style="display:flex;align-items:center;gap:8px">';
            html += '<span class="impulse-section-anim-layer-drag" style="cursor: default;color:#666"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg></span>';
            html += '<span style="font-size:11px;color:'+ImpC.text+'">Layer ' + (idx + 1) + '</span>';
            html += '</div>';
            html += '<div style="display:flex;align-items:center;gap:6px">';
            html += '<button type="button" class="impulse-section-anim-layer-delete" style="width:26px;height:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;border:1px solid '+ImpC.border+';color:'+ImpC.muted+'"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
            html += '<span class="impulse-section-anim-layer-toggle" style="color:#666;transition:transform 0.2s"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg></span>';
            html += '</div>';
            html += '</div>';
            html += '<div class="impulse-section-anim-layer-content" style="padding-top:8px">';

            

            

            var effects = [
                { v: 'rings', l: 'Rings' },
                { v: 'ring_trace', l: 'Ring Trace' },
                { v: 'burst', l: 'Burst' },
                { v: 'spiral', l: 'Spiral' },
                { v: 'starburst', l: 'Starburst' },
                { v: 'concentric', l: 'Concentric' },
                { v: 'squares', l: 'Squares' },
                { v: 'orbs', l: 'Orbs' },
                { v: 'bokeh', l: 'Bokeh' },
                { v: 'morphing', l: 'Morphing' },
                { v: 'bubbles', l: 'Bubbles' },
                { v: 'sine', l: 'Sine' },
                { v: 'aurora', l: 'Aurora' },
                { v: 'liquid', l: 'Liquid' },
                { v: 'dot_matrix', l: 'Dot Matrix' },
                { v: 'hex_grid', l: 'Hex Grid' },
                { v: 'network', l: 'Network' },
                { v: 'gradient', l: 'Gradient' },
                { v: 'caustics', l: 'Caustics' },
                { v: 'lava', l: 'Lava' }
            ];
            html += '<div class="impulse-section-anim-effect-grid" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px;margin-bottom:6px">';
            effects.forEach(function(e) {
                var isActive = false;
                var pl = window.isProEffect && window.isProEffect('sectionAnims', e.v);
                var lockA = pl ? ' data-pro-locked="1" data-pro-label="' + e.l + ' animation"' : '';
                var lockC = pl ? ' impulse-pro-locked' : '';
                html += '<button type="button" class="impulse-section-anim-effect-btn' + (isActive ? ' active' : '') + lockC + '" data-value="' + e.v + '" style="height:26px;padding:0 4px;font-size:10px;box-sizing:border-box;border:1px solid '+ImpC.border+';background:' + (isActive ? ''+ImpC.text+'' : ''+ImpC.panel+'') + ';color:' + (isActive ? ''+ImpC.surface2+'' : ''+ImpC.muted+'') + ';border-radius:3px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"' + lockA + '>' + e.l + '</button>';
            });
            html += '</div>';
            html += '<input type="hidden" class="impulse-section-anim-layer-effect" value="">';
            
            html += '<input type="hidden" class="impulse-section-anim-layer-blend" value="normal">';
            
            html += '<div class="impulse-section-anim-effect-settings">' + buildBgEffectSettingsSimple('', newLayer.settings, undefined, 0) + '</div>';
            html += '</div>';
            html += '</div>';
            
            $container.append(html);
            updateSectionAnimLayersData();
            animSaveAndUpdate();
            if (isPageSettingsMode()) refreshPreview();
        });

        
        $(document).on('click', '.impulse-section-anim-effect-btn', function() {
            var $btn = $(this);
            var effect = $btn.data('value');
            var $layer = $btn.closest('.impulse-section-anim-layer');
            var $grid = $btn.closest('.impulse-section-anim-effect-grid');

            

            var idx        = parseInt($layer.attr('data-layer-index'), 10);
            var allLayers  = _readAnimLayers();
            var layerData  = allLayers[idx] || {};
            var prevEffect = layerData.effect || '';
            layerData._effectMemory = layerData._effectMemory || {};

            if (prevEffect) {
                layerData._effectMemory[prevEffect] = JSON.parse(JSON.stringify(layerData.settings || {}));
            }

            var isAlreadyActive = $btn.hasClass('active');
            $grid.find('.impulse-section-anim-effect-btn').removeClass('active').css({background:'',color:'','border-color':''});

            var activeEffect = '';
            if (!isAlreadyActive) {
                $btn.addClass('active').css({background:'',color:'','border-color':''});
                activeEffect = effect;
            }

            
            
            var restored = (activeEffect && layerData._effectMemory[activeEffect])
                ? JSON.parse(JSON.stringify(layerData._effectMemory[activeEffect]))
                : {};
            layerData.effect   = activeEffect;
            layerData.settings = restored;
            allLayers[idx] = layerData;
            $('#impulse-section-anim-layers-data').val(JSON.stringify(allLayers));

            $layer.find('.impulse-section-anim-layer-effect').val(activeEffect);

            var currentZIndex = (function(){ var v = $layer.find('.impulse-section-anim-layer-zindex-val').val(); return (v !== '' && v !== undefined) ? parseInt(v) : 2; })();
            var $settings = $layer.find('.impulse-section-anim-effect-settings');
            $settings.html(buildBgEffectSettingsSimple(activeEffect, restored, undefined, currentZIndex));

            

            
            
            if (activeEffect) {
                var $animToggle = $('input[type="checkbox"][name="bg_animation_enabled"]');
                if ($animToggle.length && !$animToggle.is(':checked')) {
                    $animToggle.prop('checked', true).trigger('change');
                }
            }
            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });

        $(document).on('change', '.impulse-section-anim-layer-opacity', function() {
            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });
        
        $(document).on('input', '.impulse-section-anim-layer-opacity', function() {
            var val = $(this).val();
            var unit = $(this).closest('.impulse-slider-row').data('unit') || '';
            $(this).closest('.impulse-setting-row, .impulse-slider-row, .impulse-slider-with-unit').find('.impulse-slider-value').text(val + unit);
        });

        $(document).on('click', '.impulse-section-anim-layer-zindex', function() {
            var $btn = $(this);
            var val = parseInt($btn.data('value'));
            $btn.closest('.impulse-btn-group').find('.impulse-section-anim-layer-zindex').removeClass('active');
            $btn.addClass('active');
            
            $btn.closest('.impulse-btn-group').find('.impulse-section-anim-layer-zindex-val').val(String(val));

            var layerIdx = $btn.closest('.impulse-section-anim-layer').index();
            var id = $('.impulse-panel-right').data('element-id');
            var isPage = !id && isPageSettingsMode();
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                var prefix = isPage ? 'page-anim' : 'section-anim-' + id;
                iframe.contentWindow.postMessage({
                    type: 'impulse-css-update',
                    selector: '#' + prefix + '-' + layerIdx,
                    property: 'zIndex',
                    value: String(val)
                }, '*');
            }

            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });

        $(document).on('click', '.impulse-section-anim-layer-blend-btn', function() {
            var $btn = $(this);
            var $group = $btn.closest('.impulse-section-anim-blend-group');
            var value = $btn.data('value');
            
            $group.find('.impulse-section-anim-layer-blend-btn').removeClass('active');
            $btn.addClass('active');
            $group.find('.impulse-section-anim-layer-blend').val(value);
            
            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });

        $(document).on('change', '.impulse-section-anim-color-wrap .impulse-color-text', function() {
            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });

        $(document).on('click', '.impulse-bg-btn-group button', function() {
            var $btn = $(this);
            $btn.siblings().removeClass('active');
            $btn.addClass('active');
            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });

        $(document).on('change', '.impulse-section-anim-layer .impulse-bg-setting', function() {

            
            
            updateSectionAnimLayersData();
            animSaveAndUpdate();
        });

        

        
        
        $(document).on('input', '.impulse-section-anim-layer .impulse-bg-setting', function() {
            if ($(this).is('input[type="range"]')) {
                var val = $(this).val();
                var unit = $(this).closest('.impulse-slider-row').data('unit') || '';
                var $row = $(this).closest('.impulse-setting-row, .impulse-slider-with-unit');
                if (!$row.length) $row = $(this).closest('.impulse-slider-row');
                $row.find('.impulse-slider-value').text(val + unit);
            }
        });

        function updateSectionAnimLayersData() {

            
            
            var prev = [];
            try { prev = JSON.parse($('#impulse-section-anim-layers-data').val() || '[]'); } catch(e) {}
            var layers = [];
            $('.impulse-section-anim-layer').each(function(i) {
                var $layer = $(this);
                var idx     = parseInt($layer.attr('data-layer-index'), 10);
                var prevRow = (typeof idx === 'number' && !isNaN(idx)) ? prev[idx] : null;

                

                

                var settings = {};
                if (prevRow && prevRow.settings && typeof prevRow.settings === 'object') {
                    for (var pk in prevRow.settings) {
                        if (prevRow.settings.hasOwnProperty(pk)) settings[pk] = prevRow.settings[pk];
                    }
                }

                $layer.find('.impulse-bg-setting').each(function() {
                    var key = $(this).data('key');
                    var val = $(this).is(':checkbox') ? $(this).is(':checked') : $(this).val();
                    if (!isNaN(val) && val !== '' && !$(this).is(':checkbox')) {
                        val = parseFloat(val);
                    }
                    settings[key] = val;
                });

                $layer.find('.impulse-section-anim-color-wrap').each(function() {
                    var key = $(this).data('key');
                    var val = $(this).find('.impulse-color-text').val();
                    if (key && val) {
                        settings[key] = val;
                    }
                });

                $layer.find('.impulse-bg-btn-group').each(function() {
                    var key = $(this).data('key');
                    var $active = $(this).find('button.active');
                    if (key && $active.length) {
                        var val = $active.data('value');
                        settings[key] = !isNaN(val) ? parseFloat(val) : val;
                    }
                });
                var entry = {
                    effect: $layer.find('.impulse-section-anim-layer-effect').val() || '',
                    opacity: parseInt($layer.find('.impulse-section-anim-layer-opacity').val()) || 100,
                    z_index: (function(){ var v = $layer.find('.impulse-section-anim-layer-zindex-val').val(); return (v !== '' && v !== undefined) ? parseInt(v) : 2; })(),
                    blend_mode: $layer.find('.impulse-section-anim-layer-blend').val() || 'normal',
                    settings: settings
                };

                
                if (prevRow && prevRow._visible      !== undefined) entry._visible      = prevRow._visible;
                if (prevRow && prevRow._effectMemory !== undefined) entry._effectMemory = prevRow._effectMemory;
                layers.push(entry);
            });
            $('#impulse-section-anim-layers-data').val(JSON.stringify(layers));
        }

        var animSaveTimer = null;
        function animSaveAndUpdate() {
            var id = $('.impulse-panel-right').data('element-id');
            var isPageMode = !id && isPageSettingsMode();
            if (!id && !isPageMode) return;
            if (id && deletePending && deletePending[id]) return;

            var layers = [];
            try { layers = JSON.parse($('#impulse-section-anim-layers-data').val() || '[]'); } catch(e) {}
            var fullscreen = isPageMode ? true : false;

            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                var layerConfigs = [];
                layers.forEach(function(layer) {
                    var ls = layer.settings || {};
                    
                    var config = {};
                    for (var k in ls) {
                        if (ls.hasOwnProperty(k)) {
                            var v = ls[k];
                            
                            if (typeof v === 'string' && v !== '' && !isNaN(v)) {
                                config[k] = parseFloat(v);
                            } else {
                                config[k] = v;
                            }
                        }
                    }

                    

                    config.effect = layer.effect || '';
                    config.opacity = layer.opacity !== undefined && layer.opacity !== '' ? parseFloat(layer.opacity) : 100;
                    config.blend_mode = layer.blend_mode || 'normal';
                    config.z_index = layer.z_index !== undefined ? parseInt(layer.z_index) : 0;

                    
                    config._visible = layer._visible !== false;
                    
                    if (config.color === undefined) config.color = '#888888';
                    if (config.speed === undefined) config.speed = 1;
                    if (config.origin_x === undefined) config.origin_x = 50;
                    if (config.origin_y === undefined) config.origin_y = 50;
                    layerConfigs.push(config);
                });
                iframe.contentWindow.postMessage({
                    type: 'impulse-update-animation',
                    sectionId: isPageMode ? 'page' : id,
                    layers: layerConfigs,
                    fullscreen: fullscreen
                }, '*');
            }

            clearTimeout(animSaveTimer);
            showSaveStatus(true);
            animSaveTimer = setTimeout(function() {
                if (isPageMode) {
                    
                    var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                    var settings = collectSettingsFromPanel(existingSettings);

                    

                    ['animation_layers'].forEach(function(key) {
                        if (typeof settings[key] === 'string') {
                            try { settings[key] = JSON.parse(settings[key]); } catch(e) {}
                        }
                    });

                    var mergedSettings = $.extend({}, existingSettings, settings);
                    Impulse.pageSettings = mergedSettings;
                    $('.impulse-panel-right').data('existing-settings', mergedSettings);
                    
                    $.ajax({
                        url: Impulse.api + 'pages/' + Impulse.pageId,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                        success: function() { showSaveStatus(); }
                    });
                } else {
                    
                    if (deletePending && deletePending[id]) return;
                    var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                    var settings = collectSettingsFromPanel(existingSettings);
                    var mergedSettings = $.extend({}, existingSettings, settings);
                    
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                        success: function() {
                            if (deletePending && deletePending[id]) return;
                            $('.impulse-panel-right').data('existing-settings', mergedSettings);
                            showSaveStatus();
                        }
                    });
                }
            }, 300);
        }

        if (typeof Sortable !== 'undefined') {
            $(document).on('DOMNodeInserted', '.impulse-section-anim-layers-container', function() {
                var container = document.querySelector('.impulse-section-anim-layers-container');
                if (container && !container.sortableInstance) {
                    container.sortableInstance = new Sortable(container, {
                        animation: 150,
                        handle: '.impulse-section-anim-layer-drag',
                        onEnd: function() {
                            $('.impulse-section-anim-layer').each(function(i) {
                                $(this).attr('data-layer-index', i);
                                $(this).find('.impulse-section-anim-layer-header span:eq(1)').text('Layer ' + (i + 1));
                            });
                            updateSectionAnimLayersData();
                            autoSaveAndRefresh();
                        }
                    });
                }
            });
        }

        
        var bgShapeInsertMode = null; 

        function getBgShapes() {
            var json = $('textarea[name="bg_shapes"]').val() || '[]';
            try { return JSON.parse(json); } catch(e) { return []; }
        }

        

        
        
        var _bgShapeSaveTimer = null;
        function saveBgShapes(shapes) {
            var json = JSON.stringify(shapes);
            $('textarea[name="bg_shapes"]').val(json);
            var $panel = $('.impulse-panel-right');
            var id = $panel.data('element-id');
            if (!id) return;
            
            var existingSettings = $panel.data('existing-settings') || {};
            existingSettings.bg_shapes = json;
            $panel.data('existing-settings', existingSettings);

            
            
            clearTimeout(_bgShapeSaveTimer);
            _bgShapeSaveTimer = setTimeout(function() {
                var current = $panel.data('existing-settings') || {};
                var merged = $.extend({}, current, { bg_shapes: json });
                showSaveStatus(true);
                enqueueSave(id, merged, function(success) {
                    if (!success) return;
                    if ($panel.data('element-id') == id) {
                        $panel.data('existing-settings', merged);
                    }
                    showSaveStatus();
                });
            }, 80);
        }

        

        

        

        function addLibraryShapeToBg(shape, isImage) {
            if (!shape) return false;
            var $panel = $('.impulse-panel-right');
            if (!$panel.data('element-id') || $('textarea[name="bg_shapes"]').length === 0) {
                if (typeof window.showToast === 'function') {
                    window.showToast('Select a section first, then click a shape to add it to the background', 'error');
                }
                return false;
            }
            var newShape = {
                uid: 'shp_' + Math.random().toString(36).substr(2, 8),
                name: shape.name || (isImage ? 'Graphic' : 'Shape'),
                anchor: 'cc', ox: 0, oy: 0,
                size_pct: 30, rotation: 0, opacity: 100,
                flip_h: false, visible: true
            };
            if (isImage) {
                newShape.type = 'image';
                newShape.image_url = shape.image_url || shape.url || '';
            } else {
                newShape.svg = shape.svg || '';
                newShape.viewbox = shape.viewbox || '0 0 24 24';
                var colors = ['#999999'];
                if (shape.default_colors && Array.isArray(shape.default_colors) && shape.default_colors.length > 0) {
                    colors = shape.default_colors.slice();
                } else if (shape.color_count > 1 || (shape.svg && shape.svg.indexOf('data-c=') !== -1)) {
                    var maxC = 0;
                    var matches = (shape.svg || '').match(/data-c="(\d+)"/g);
                    if (matches) { matches.forEach(function(m) { var n = parseInt(m.match(/\d+/)[0]); if (n > maxC) maxC = n; }); }
                    colors = [];
                    var fp = ['#999999','#cccccc','#666666','#aaaaaa','#888888','#bbbbbb','#777777','#cccccc'];
                    for (var ci = 0; ci < maxC; ci++) { colors.push(fp[ci % fp.length]); }
                }
                newShape.colors = colors;
            }
            var shapes = getBgShapes();
            shapes.push(newShape);
            saveBgShapes(shapes);

            

            var type = $panel.data('element-type') || 'section';
            var existingSettings = $panel.data('existing-settings') || {};
            existingSettings.bg_shapes = JSON.stringify(shapes);
            renderSettingsPanel(type, existingSettings);

            bgShapeInsertMode = null;
            if (typeof window.showToast === 'function') window.showToast('Shape added to background');
            refreshPreview();
            return true;
        }

        window.addLibraryShapeToBg = addLibraryShapeToBg;

        $(document).on('click', '.impulse-bg-shape-anchor-btn', function(e) {
            e.preventDefault();
            var $this = $(this);
            var idx = parseInt($this.data('idx'));
            var anchor = $this.data('anchor');
            $this.addClass('active').siblings().removeClass('active');

            var shapes = getBgShapes();
            if (shapes[idx]) {
                var device = window.impulseDevice || 'desktop';
                var key = device === 'desktop' ? 'anchor' : 'anchor_' + device;
                shapes[idx][key] = anchor;
                saveBgShapes(shapes);
                livePreviewBgShape(idx, shapes[idx]);
            }
        });

        
        
        $(document).on('input', '.impulse-bg-shape-ctrl', function() {
            var $this = $(this);
            var idx = parseInt($this.data('idx'));
            var prop = $this.data('prop');
            var unit = $this.data('unit') || '';
            var val = parseInt($this.val()) || 0;

            var $row = $this.closest('.impulse-setting-row');
            $row.find('.impulse-slider-value').text(val + unit);

            var shapes = getBgShapes();
            if (shapes[idx]) {
                var device = window.impulseDevice || 'desktop';
                var key = device === 'desktop' ? prop : prop + '_' + device;
                shapes[idx][key] = val;
                saveBgShapes(shapes);
                livePreviewBgShape(idx, shapes[idx]);
            }
        });

        
        $(document).on('click', '.impulse-bg-shape-flip', function() {
            var idx = parseInt($(this).data('idx'));
            var shapes = getBgShapes();
            if (shapes[idx]) {
                var device = window.impulseDevice || 'desktop';
                var key = device === 'desktop' ? 'flip_h' : 'flip_h_' + device;
                var current = shapes[idx][key] || false;
                shapes[idx][key] = !current;
                var flipped = shapes[idx][key];
                $(this).css({borderColor: flipped ? ''+ImpC.dim+'' : ''+ImpC.border+'', background: flipped ? ''+ImpC.border+'' : ''+ImpC.panel+'', color: flipped ? ''+ImpC.text+'' : ''+ImpC.muted+''});
                saveBgShapes(shapes);
                livePreviewBgShape(idx, shapes[idx]);
            }
        });

        

        
        
        $(document).on('click', '.impulse-bg-shape-remove', function(e) {
            e.stopPropagation();
            var idx = parseInt($(this).data('idx'));
            var shapes = getBgShapes();
            shapes.splice(idx, 1);
            saveBgShapes(shapes);
            var iframe = document.getElementById('impulse-iframe');
            var idoc = iframe && iframe.contentDocument;
            if (idoc) {
                var layer = idoc.querySelector('.impulse-el[data-id="' + selectedElementId + '"] .impulse-bg-shape-layer');
                if (layer) {
                    var gone = layer.querySelector('[data-shape-idx="' + idx + '"]');
                    if (gone && gone.parentNode) gone.parentNode.removeChild(gone);
                    layer.querySelectorAll('[data-shape-idx]').forEach(function(node) {
                        var i = parseInt(node.getAttribute('data-shape-idx'), 10);
                        if (i > idx) node.setAttribute('data-shape-idx', i - 1);
                    });
                }
            }
            var type = $('.impulse-panel-right').data('element-type') || 'section';
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            existingSettings.bg_shapes = JSON.stringify(shapes);
            renderSettingsPanel(type, existingSettings);
        });

        

        

        $(document).on('click', '.impulse-color-swap', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var n1 = this.getAttribute('data-c1') || '';
            var n2 = this.getAttribute('data-c2') || '';
            if (!n1 || !n2) return;

            var $scope = $(this).closest('#impulse-settings-body, #impulse-screen-bar');
            if (!$scope.length) $scope = $(document);
            var $i1 = $scope.find('input[name="' + n1 + '"].impulse-color-text').first();
            var $i2 = $scope.find('input[name="' + n2 + '"].impulse-color-text').first();
            if (!$i1.length || !$i2.length) return;
            var v1 = $i1.val() || '';
            var v2 = $i2.val() || '';

            

            

            

            

            var fillName = null;

            
            
            var n2Stripped = n2
                .replace(/_grad(ient)?_(to|2)$/i, '_fill')
                .replace(/_grad(ient)?_(to|2)_(\d+)$/i, '_fill_$3');
            if (n2Stripped !== n2 && $scope.find('input[name="' + n2Stripped + '"]').length) {
                fillName = n2Stripped;
            }
            var $fill = fillName ? $scope.find('input[name="' + fillName + '"]').first() : $();

            if (v1 !== v2) {
                $i1.val(v2);
                $i2.val(v1);
                $i1.closest('.impulse-color-setting').find('.impulse-color-swatch').css('--swatch-color', v2 || 'transparent');
                $i2.closest('.impulse-color-setting').find('.impulse-color-swatch').css('--swatch-color', v1 || 'transparent');
            }

            if ($fill.length) {
                var cur = ($fill.val() || 'solid').toString();
                var next = (cur === 'gradient') ? 'solid' : 'gradient';
                $fill.val(next).trigger('input').trigger('change');
            }

            
            $i1.trigger('input').trigger('change');
            $i2.trigger('input').trigger('change');
        });

        

        $(document).on('input change', '.impulse-bg-shape-color-text', function(e) {
            e.stopPropagation();
            var $input = $(this);
            var idx  = parseInt($input.data('idx'));
            var cidx = parseInt($input.data('cidx') || 0);
            var newColor = $input.val();
            if (!newColor) return;

            var shapes = getBgShapes();
            var shape = shapes[idx];
            if (!shape) return;
            var colors = shape.colors || ['#999999'];
            if (colors[cidx] === newColor) return; 
            colors[cidx] = newColor;
            shape.colors = colors;

            var $swatch = $input.siblings('.impulse-color-swatch');
            $swatch.css('--swatch-color', newColor);
            if (cidx === 0) {
                $swatch.closest('.impulse-bg-shape-item').find('.impulse-bg-shape-head svg').first().attr('fill', newColor);
            }
            saveBgShapes(shapes);
            livePreviewBgShape(idx, shape);
        });

        $(document).on('click', '.impulse-bg-shape-add', function() {
            bgShapeInsertMode = selectedElementId;
            
            $('.impulse-panel-tab').removeClass('active');
            $('.impulse-panel-tab[data-tab="templates"]').addClass('active');
            $('.impulse-blocks-panel, .impulse-structure-panel').hide();
            $('.impulse-templates-panel').show();
            
            $('.impulse-library-subtab').removeClass('active');
            $('.impulse-library-subtab[data-subtab="graphics"]').addClass('active');
            $('.impulse-library-content').removeClass('active');
            $('.impulse-library-graphics').addClass('active');
            loadShapesLibrary();
        });

        $(document).on('click', '.impulse-shape-item', function() {
            var shape = $(this).data('shape-data');
            if (!shape) return;

            
            addLibraryShapeToBg(shape, false);
        });

        $(document).on('dragstart', '.impulse-image-item', function(e) {
            var graphic = $(this).data('graphic-data');
            if (!graphic) return;
            draggedElement = 'graphic:' + graphic.id;
            e.originalEvent.dataTransfer.setData('text/plain', 'graphic:' + graphic.id);
            e.originalEvent.dataTransfer.effectAllowed = 'copy';
            window._draggedGraphicData = graphic;
            isDragActive = true;
            $('.impulse-canvas').addClass('drag-active');
            var iframe = document.getElementById('impulse-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: 'impulse-drag-start', element: 'graphic:' + graphic.id }, '*');
            }
        });
        
        $(document).on('dragend', '.impulse-image-item', function() {
            $('.impulse-canvas').removeClass('drag-over drag-active');
            isDragActive = false;
            if (pendingRefresh) { pendingRefresh = false; refreshPreview(); }
            draggedElement = null;
        });

        function ensureSectionExists(targetId, callback) {
            
            if (targetId && (selectedElementType === 'section' || selectedElementType === 'grid' || selectedElementType === 'rows')) {
                callback(targetId);
                return;
            }
            
            window.showToast('Creating section...');
            addElementWithSettings('section', {}, null, 999999, function(newId) {
                setTimeout(function() {
                    
                    selectedElementId = newId;
                    selectedElementType = 'section';
                    callback(newId);
                }, 200);
            });
        }

        
        function downloadGraphicLocal(remoteUrl, callback) {
            $.post(Impulse.ajaxUrl, {
                action: 'instinctor_download_graphic',
                nonce: Impulse.graphicDownloadNonce,
                url: remoteUrl
            }, function(r) {
                if (r.success && r.data && r.data.local_url) {
                    callback(r.data.local_url);
                } else {
                    callback(remoteUrl);
                }
            }).fail(function() {
                callback(remoteUrl);
            });
        }
        
        $(document).on('click', '.impulse-image-item', function() {
            var graphic = $(this).data('graphic-data');
            if (!graphic) return;

            

            if (!$('.impulse-panel-right').data('element-id') || $('textarea[name="bg_shapes"]').length === 0) {
                if (typeof window.showToast === 'function') {
                    window.showToast('Select a section first, then click a graphic to add it to the background', 'error');
                }
                return;
            }
            downloadGraphicLocal(graphic.image_url, function(localUrl) {
                addLibraryShapeToBg({ name: graphic.name, image_url: localUrl }, true);
            });
        });

        
        $(document).on('click', '.impulse-panel-tab:not([data-tab="templates"])', function() {
            bgShapeInsertMode = null;
        });

        function bgShapeAnchorPos(anchor) {

            
            
            switch (anchor) {
                case 'tl': return { left: '0',    top: '0',    tx: '0',    ty: '0' };
                case 'tr': return { left: '100%', top: '0',    tx: '-100%', ty: '0' };
                case 'bl': return { left: '0',    top: '100%', tx: '0',    ty: '-100%' };
                case 'br': return { left: '100%', top: '100%', tx: '-100%', ty: '-100%' };
                case 'cc':
                default:   return { left: '50%',  top: '50%',  tx: '-50%', ty: '-50%' };
            }
        }

        
        
        function livePreviewBgShape(idx, shape) {
            var iframe = document.getElementById('impulse-iframe');
            if (!iframe || !iframe.contentDocument) return;
            var elId = selectedElementId;
            var device = window.impulseDevice || 'desktop';
            var el = iframe.contentDocument.querySelector('.impulse-el[data-id="' + elId + '"] .impulse-bg-shape-layer [data-shape-idx="' + idx + '"]');
            if (!el) return;

            var anchor  = getDeviceVal(shape, 'anchor',   device, shape.anchor || 'cc');
            var ox      = getDeviceVal(shape, 'ox',       device, shape.ox !== undefined ? shape.ox : 0);
            var oy      = getDeviceVal(shape, 'oy',       device, shape.oy !== undefined ? shape.oy : 0);
            var sizePct = getDeviceVal(shape, 'size_pct', device, shape.size_pct !== undefined ? shape.size_pct : 30);
            var op      = getDeviceVal(shape, 'opacity',  device, shape.opacity !== undefined ? shape.opacity : 100);
            var rot     = getDeviceVal(shape, 'rotation', device, shape.rotation || 0);
            var vis     = getDeviceVal(shape, 'visible',  device, shape.visible !== false);
            var flipH   = getDeviceVal(shape, 'flip_h',   device, shape.flip_h || false);

            var ap = bgShapeAnchorPos(anchor);
            el.style.left = ap.left;
            el.style.top = ap.top;
            el.style.width = sizePct + '%';
            el.style.aspectRatio = '1';
            el.style.setProperty('--tx', ap.tx);
            el.style.setProperty('--ty', ap.ty);
            el.style.setProperty('--ox', ox + 'cqw');
            el.style.setProperty('--oy', oy + 'cqw');
            el.style.setProperty('--rot', rot + 'deg');
            el.style.setProperty('--flip', flipH ? '-1' : '1');
            el.style.transform = 'translate(var(--tx),var(--ty)) translate(var(--ox),var(--oy)) rotate(var(--rot)) scaleX(var(--flip))';
            el.style.opacity = vis ? (op / 100) : 0;
            el.dataset.anchor = anchor;

            var primary = (shape.colors && shape.colors[0]) || shape.color || ImpC.muted;
            el.style.color = primary;
            var svg = el.querySelector('svg');
            if (svg) svg.setAttribute('fill', primary);
            var colors = shape.colors || [primary];
            colors.forEach(function(c, ci) {
                el.style.setProperty('--c' + (ci + 1), c);
            });
        }

        window.addEventListener('message', function(e) {
            if (e.data && e.data.type === 'impulse-bg-shape-drag') {
                var shapes = getBgShapes();
                var idx = e.data.idx;
                if (shapes[idx]) {
                    var device = window.impulseDevice || 'desktop';
                    var kx = device === 'desktop' ? 'ox' : 'ox_' + device;
                    var ky = device === 'desktop' ? 'oy' : 'oy_' + device;
                    var nx = Math.round(e.data.ox);
                    var ny = Math.round(e.data.oy);
                    shapes[idx][kx] = nx;
                    shapes[idx][ky] = ny;

                    var $ox = $('.impulse-bg-shape-ctrl[data-idx="' + idx + '"][data-prop="ox"]');
                    var $oy = $('.impulse-bg-shape-ctrl[data-idx="' + idx + '"][data-prop="oy"]');
                    if ($ox.length) {
                        $ox.val(nx);
                        $ox.closest('.impulse-setting-row').find('.impulse-slider-value').text(nx + '%');
                    }
                    if ($oy.length) {
                        $oy.val(ny);
                        $oy.closest('.impulse-setting-row').find('.impulse-slider-value').text(ny + '%');
                    }

                    saveBgShapes(shapes);
                }
            }
        });

        
        
        $(document).on('click', '.impulse-add-menu-item', function() {
            var $list = $('.impulse-header-menu-items');
            var idx = $list.find('.impulse-header-menu-item').length;
            var html = '<div class="impulse-header-menu-item" data-index="' + idx + '" style="display:flex;gap:6px;margin-bottom:6px">';
            html += '<input type="text" name="menu_label_' + idx + '" value="" placeholder="Label" style="flex:1;min-width:0;padding:0 6px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;background:'+ImpC.panel+';color:'+ImpC.text+'">';
            html += '<input type="text" name="menu_url_' + idx + '" value="#" placeholder="URL" style="flex:1;min-width:0;padding:0 6px;border:1px solid '+ImpC.border+';border-radius:3px;font-size:11px;background:'+ImpC.panel+';color:'+ImpC.text+'">';
            html += '<button type="button" class="impulse-remove-menu-item" style="width:26px;flex-shrink:0;background:'+ImpC.panel+';border:1px solid '+ImpC.border+';border-radius:3px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0" title="Remove"><svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="'+ImpC.muted+'" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
            html += '</div>';
            $list.append(html);
            gatherAndSaveMenuItems(true); 
        });

        $(document).on('click', '.impulse-remove-menu-item', function() {
            $(this).closest('.impulse-header-menu-item').remove();
            
            $('.impulse-header-menu-item').each(function(i) {
                $(this).attr('data-index', i);
                $(this).find('input').first().attr('name', 'menu_label_' + i);
                $(this).find('input').last().attr('name', 'menu_url_' + i);
            });
            gatherAndSaveMenuItems(true); 
        });

        $(document).on('input', '.impulse-header-menu-item input', function() {
            gatherAndSaveMenuItems();
        });

        var menuSaveTimer = null;
        function gatherAndSaveMenuItems(triggerRefresh) {
            var menuItems = [];
            $('.impulse-header-menu-item').each(function() {
                var label = $(this).find('input[name^="menu_label"]').val() || '';
                var url = $(this).find('input[name^="menu_url"]').val() || '';
                if (label || url) {
                    menuItems.push({label: label, url: url});
                }
            });
            
            var id = $('.impulse-panel-right').data('element-id');
            if (id) {
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                existingSettings.menu_items = menuItems;
                $('.impulse-panel-right').data('existing-settings', existingSettings);

                clearTimeout(menuSaveTimer);
                menuSaveTimer = setTimeout(function() {
                    var settings = collectSettingsFromPanel(existingSettings);
                    var mergedSettings = $.extend({}, existingSettings, settings);
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                        success: function() {
                            $('.impulse-panel-right').data('existing-settings', mergedSettings);
                            if (triggerRefresh) {
                                refreshPreview();
                            }
                        }
                    });
                }, 500);
            }
        }

        

        $(document).on('click', '.impulse-save-header-to-library', function() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) { window.showToast('No header selected'); return; }
            saveAsTemplateById(id);
        });

        $(document).on('click', '.impulse-save-footer-to-library', function() {
            var id = $('.impulse-panel-right').data('element-id');
            if (!id) { window.showToast('No footer selected'); return; }
            if (typeof gatherFooterLinksSync === 'function') gatherFooterLinksSync();
            saveAsTemplateById(id);
        });

        
        $(document).on('click', '.impulse-remove-footer-link', function(e) {
            e.stopPropagation();
            $(this).closest('.impulse-footer-link-item').remove();
            gatherAndSaveFooterLinks();
        });

        $(document).on('click', '.impulse-footer-link-url-btn', function() {
            var $row = $(this).closest('.impulse-footer-link-item');
            var $input = $row.find('.impulse-footer-link-text');
            var $btn = $(this);
            var isUrlMode = $row.hasClass('impulse-url-mode');
            
            if (isUrlMode) {
                
                $row.data('url', $input.val());
                $row.attr('data-url', $input.val());
                $row.removeClass('impulse-url-mode');
                
                var col = $row.closest('.impulse-footer-column-links').data('col');
                var idx = $row.index();
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var links = existingSettings[col + '_links'] || [];
                var label = (links[idx] && links[idx].label) || '';
                $input.val(label).attr('placeholder', 'Link label');
                $btn.css({'background': ''+ImpC.panel+'', 'border-color': ''+ImpC.border+''}).find('svg').attr('stroke', ''+ImpC.muted+'');
            } else {
                
                var currentLabel = $input.val();
                var col = $row.closest('.impulse-footer-column-links').data('col');
                var idx = $row.index();
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                var links = existingSettings[col + '_links'] || [];
                if (!links[idx]) links[idx] = {};
                links[idx].label = currentLabel;
                existingSettings[col + '_links'] = links;
                $('.impulse-panel-right').data('existing-settings', existingSettings);
                
                $row.addClass('impulse-url-mode');
                var storedUrl = $row.attr('data-url') || $row.data('url') || '';
                $input.val(storedUrl).attr('placeholder', 'https://');
                $btn.css({'background': ''+ImpC.text+'', 'border-color': ''+ImpC.border+''}).find('svg').attr('stroke', ''+ImpC.surface2+'');
            }
        });

        $(document).on('input', '.impulse-footer-link-text', function() {
            var $row = $(this).closest('.impulse-footer-link-item');
            if ($row.hasClass('impulse-url-mode')) {
                $row.data('url', $(this).val());
                $row.attr('data-url', $(this).val());
            }
            gatherAndSaveFooterLinks();
        });

        $(document).on('input', '.impulse-footer-col-title', function() {
            if (selectedElementType === 'footer') {
                autoSaveAndRefresh();
            }
        });

        $(document).on('click', '.impulse-footer-col-trigger', function(e) {
            if ($(e.target).is('input')) return; 
            var $section = $(this).closest('.impulse-footer-col-section');
            var $content = $section.find('.impulse-footer-col-content');
            var $chevron = $section.find('.impulse-footer-col-chevron');
            
            if ($section.hasClass('collapsed')) {
                $section.removeClass('collapsed');
                $content.slideDown(150);
                $chevron.css('transform', 'rotate(0deg)');
            } else {
                $section.addClass('collapsed');
                $content.slideUp(150);
                $chevron.css('transform', 'rotate(-90deg)');
            }
        });

        $('.impulse-footer-col-section.collapsed .impulse-footer-col-chevron').css('transform', 'rotate(-90deg)');

        var footerLinkSaveTimer = null;
        function gatherAndSaveFooterLinks() {
            gatherFooterLinksSync();
            var id = $('.impulse-panel-right').data('element-id');
            if (id) {
                var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
                clearTimeout(footerLinkSaveTimer);
                footerLinkSaveTimer = setTimeout(function() {
                    var settings = collectSettingsFromPanel(existingSettings);
                    var mergedSettings = $.extend({}, existingSettings, settings);
                    $.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: mergedSettings, page_id: Impulse.pageId }),
                        success: function() {
                            $('.impulse-panel-right').data('existing-settings', mergedSettings);
                            refreshPreview();
                        }
                    });
                }, 500);
            }
        }

        function gatherFooterLinksSync() {
            var cols = ['col1', 'col2', 'col3'];
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            cols.forEach(function(col) {
                var links = [];
                var existingLinks = existingSettings[col + '_links'] || [];
                $('.impulse-footer-column-links[data-col="' + col + '"] .impulse-footer-link-item').each(function(i) {
                    var $row = $(this);
                    var isUrlMode = $row.hasClass('impulse-url-mode');
                    var inputVal = $row.find('.impulse-footer-link-text').val() || '';
                    var label, url;
                    if (isUrlMode) {
                        url = inputVal;
                        label = (existingLinks[i] && existingLinks[i].label) || '';
                    } else {
                        label = inputVal;
                        url = $row.attr('data-url') || '';
                    }
                    if (label || url) {
                        links.push({label: label, url: url});
                    }
                });
                existingSettings[col + '_links'] = links;
            });
            $('.impulse-panel-right').data('existing-settings', existingSettings);
        }

    }
    
    function upgradeCheckboxes(container) {
        $(container).find('input[type="checkbox"]').not('.impulse-cb-hidden').each(function() {
            var $cb  = $(this);
            var $div = $('<div class="impulse-cb"></div>');
            if ($cb.is(':checked'))  $div.addClass('active');
            if ($cb.is(':disabled')) $div.addClass('disabled');
            $cb.before($div);
            $cb.addClass('impulse-cb-hidden');
            
            $div.on('click', function(e) {
                e.stopPropagation();
                if ($div.hasClass('disabled')) return;
                var nowChecked = !$cb.is(':checked');
                $cb.prop('checked', nowChecked);
                $div.toggleClass('active', nowChecked);
                $cb.trigger('change');
            });
            
            var $label = $cb.closest('label');
            if ($label.length) {
                $label.on('click.cbproxy', function(e) {
                    
                    if (!$(e.target).hasClass('impulse-cb')) {
                        e.preventDefault();
                        $div.trigger('click');
                    }
                });
            }
            
            $cb.on('change.cbsync', function() {
                $div.toggleClass('active', $cb.is(':checked'));
            });
        });
    }
    window.upgradeCheckboxes = upgradeCheckboxes;

    $(function() {
        upgradeCheckboxes(document.getElementById('impulse-settings-body'));

        
        upgradeCheckboxes(document.getElementById('impulse-chat-toggle-footer'));
    });

    var _cbObserver = new MutationObserver(function(mutations) {
        mutations.forEach(function(m) {
            if (m.addedNodes.length) upgradeCheckboxes(m.target);
        });
    });
    $(function() {
        var settingsBody = document.getElementById('impulse-settings-body');
        if (settingsBody) {
            _cbObserver.observe(settingsBody, { childList: true });
        }
    });

    

    

    
    function captureBatchEmpty(all) {
        var iframe = document.getElementById('impulse-iframe');
        if (!iframe) {
            alert('Editor iframe missing — open the admin canvas first.');
            return;
        }

        var $overlay = $(
            '<div id="impulse-capture-batch-overlay" style="position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:99999;display:flex;align-items:center;justify-content:center;color:#fff;font:14px/1.5 -apple-system,BlinkMacSystemFont,sans-serif">'
          +   '<div style="background:#1d2327;padding:24px 32px;border-radius:8px;min-width:360px;max-width:520px;text-align:center">'
          +     '<div style="font-size:13px;color:#999;letter-spacing:0.05em;text-transform:uppercase;margin-bottom:10px">Batch capture</div>'
          +     '<div id="impulse-capture-batch-status">Fetching pages…</div>'
          +     '<div style="margin-top:14px;width:100%;height:4px;background:#2a2f33;border-radius:2px;overflow:hidden">'
          +       '<div id="impulse-capture-batch-fill" style="width:0%;height:100%;background:#fff;transition:width 0.3s"></div>'
          +     '</div>'
          +     '<div id="impulse-capture-batch-action" style="margin-top:14px;font-size:12px;color:#888;cursor:pointer">cancel</div>'
          +   '</div>'
          + '</div>'
        );
        $('body').append($overlay);

        var cancelled = false;
        $('#impulse-capture-batch-action').on('click', function() {
            if (cancelled) { $overlay.remove(); return; }
            cancelled = true;
        });

        function setStatus(msg)   { $('#impulse-capture-batch-status').text(msg); }
        function setProgress(pct) { $('#impulse-capture-batch-fill').css('width', pct + '%'); }
        function finish(msg) {
            cancelled = true;
            setStatus(msg);
            $('#impulse-capture-batch-action').text('close');
        }

        

        
        function _waitForCaptureReady(ifr, cb) {
            var doc, start = Date.now(), IMGMAX = 6000;
            try { doc = ifr.contentDocument; } catch (e) { setTimeout(cb, 3500); return; }
            if (!doc) { setTimeout(cb, 3500); return; }
            (function pollImgs() {
                var imgs = [].slice.call(doc.images || []);
                if (Date.now() - start < IMGMAX && imgs.some(function(im) { return !im.complete; })) {
                    setTimeout(pollImgs, 300); return;
                }
                var hasCanvas = !!doc.querySelector('canvas');
                setTimeout(cb, hasCanvas ? 3500 : 1200);
            })();
        }

        $.ajax({
            url: Impulse.api + 'pages/empty-thumbnails' + (all ? '?all=1' : ''),
            method: 'GET',
            headers: { 'X-WP-Nonce': Impulse.nonce }
        }).done(function(data) {
            var pages = (data && data.pages) || [];
            if (!pages.length) { finish(all ? 'No published pages to capture.' : 'Nothing to capture — all pages have thumbnails.'); return; }
            var total = pages.length;
            var idx = 0;
            var doneCount = 0;
            var failCount = 0;

            function next() {
                if (cancelled && idx < total) {
                    finish('Stopped at ' + idx + '/' + total + ' (' + doneCount + ' captured, ' + failCount + ' failed).');
                    return;
                }
                if (idx >= total) {
                    finish('Done — ' + doneCount + ' captured, ' + failCount + ' failed.');
                    return;
                }
                var p = pages[idx];
                setStatus('Capturing ' + (idx + 1) + '/' + total + ' — ' + (p.name || ('Page ' + p.id)));
                setProgress((idx / total) * 100);

                var url = location.protocol + '//' + location.host
                        + '/admin/preview/' + p.id + '?edit=1&device=desktop&t=' + Date.now();

                
                showThumbSpinner(p.id);

                var settled = false;
                function advance(success) {
                    if (settled) return;
                    settled = true;
                    window.removeEventListener('message', onMsg);
                    hideThumbSpinner(p.id);
                    if (success) doneCount++; else failCount++;
                    idx++;
                    setTimeout(next, 250);
                }

                function onMsg(e) {
                    if (!e.data || e.data.type !== 'impulse-thumbnail-captured') return;
                    if (String(e.data.pageId) !== String(p.id)) return;
                    advance(!!e.data.dataUrl);
                }
                window.addEventListener('message', onMsg);

                
                
                iframe.onload = function() {
                    iframe.onload = null;
                    if (cancelled) { advance(false); return; }

                    
                    _waitForCaptureReady(iframe, function() {
                        if (cancelled) { advance(false); return; }
                        try {
                            iframe.contentWindow.postMessage({ type: 'impulse-capture-thumbnail' }, '*');
                        } catch (e) {
                            advance(false);
                        }
                    });
                };
                iframe.src = url;

                

                setTimeout(function() { advance(false); }, 24000);
            }

            next();
        }).fail(function() {
            finish('Failed to load empty-thumbnails list.');
        });
    }
    window.captureBatchEmpty = captureBatchEmpty;

    
    $(function() {
        try {
            var params = new URLSearchParams(location.search);
            if (params.get('capture-empty') === '1') {
                setTimeout(captureBatchEmpty, 1500);
            }
        } catch (e) {}
    });

    window.lucideSvg              = lucideSvg;
    window.switchWorkspace        = switchWorkspace;
    window.impulseConfirm         = impulseConfirm;
    window.impulsePrompt          = impulsePrompt;
    window.positionWorkspaceTrack = positionWorkspaceTrack;

    

});

(function(){
    function noImage(){
        var $hidden = jQuery('.impulse-panel-right input[name="image_id"]');
        var hasId = $hidden.length && $hidden.val();
        var $src  = jQuery('.impulse-panel-right input[name="image_src"]');
        var hasSrc = $src.length && $src.val();
        return !hasId && !hasSrc;
    }
    function guard(label){
        if (noImage()) {
            if (typeof showImpulseToast === 'function') showImpulseToast('Select an image first');
            return true;
        }
        return false;
    }

    jQuery(document).on('click', '.impulse-image-edge-canvas', function(e){
        if (guard()) { e.preventDefault(); e.stopImmediatePropagation(); }
    });
})();

window.ImpulseCropBridge = (function(){
    var _configs = {};

    

    var SUFFIXES_LEGACY  = ['top','right','bottom','left',
                            'top_c','right_c','bottom_c','left_c'];
    var SUFFIXES_CORNERS = ['tl','tr','br','bl'];
    var SUFFIXES_CTRLS   = ['top_c1','top_c2','right_c1','right_c2',
                            'bottom_c1','bottom_c2','left_c1','left_c2'];
    var SUFFIXES_NODES   = ['top_nodes','right_nodes','bottom_nodes','left_nodes'];
    var SUFFIXES_TANG    = ['tl_tangent','tr_tangent','br_tangent','bl_tangent'];

    var ALL_SUFFIXES = SUFFIXES_LEGACY
        .concat(SUFFIXES_CORNERS)
        .concat(SUFFIXES_CTRLS)
        .concat(SUFFIXES_NODES)
        .concat(SUFFIXES_TANG);

    function register(blockType, cfg) {
        
        _configs[blockType] = cfg;
    }

    function getConfigForElement(elId) {
        if (!elId) return null;
        var ifr = document.getElementById('impulse-iframe');
        var doc = ifr && ifr.contentDocument;
        var el = doc && doc.querySelector('.impulse-el[data-id="' + elId + '"]');
        if (!el) return null;
        var t = el.getAttribute('data-type');
        return _configs[t] || null;
    }

    function renderHiddenInputs(prefix, settings) {
        var esc = function(v) {

            
            if (typeof escapeHtml === 'function') return escapeHtml(v);
            return String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
        };
        var html = '';
        
        SUFFIXES_LEGACY.forEach(function(suf){
            var v = settings[prefix + suf];
            if (v === undefined || v === null) v = (['top','right','bottom','left'].indexOf(suf) !== -1) ? 0 : '';
            html += '<input type="hidden" name="' + prefix + suf + '" value="' + esc(v) + '">';
        });
        SUFFIXES_CORNERS.concat(SUFFIXES_CTRLS).concat(SUFFIXES_TANG).forEach(function(suf){
            html += '<input type="hidden" name="' + prefix + suf + '" value="' + esc(settings[prefix + suf] || '') + '">';
        });
        
        SUFFIXES_NODES.forEach(function(suf){
            html += '<input type="hidden" name="' + prefix + suf + '" value="' + esc(settings[prefix + suf] || '') + '">';
        });
        return html;
    }

    

    

    function hasCropApplied(settings, prefix, deviceSuffix) {
        settings = settings || {};
        var sfx = deviceSuffix || '';
        function val(suf) {
            
            if (sfx) {
                var dv = settings[prefix + suf + sfx];
                if (dv !== undefined && dv !== null && dv !== '') return dv;
            }
            return settings[prefix + suf];
        }

        if (SUFFIXES_CORNERS.some(function(s){ return String(val(s) || '') !== ''; })) return true;
        
        if (SUFFIXES_CTRLS.some(function(s){ return String(val(s) || '') !== ''; })) return true;
        
        if (SUFFIXES_NODES.some(function(s){ var v = String(val(s) || ''); return v !== '' && v !== '[]'; })) return true;
        
        if (SUFFIXES_TANG.some(function(s){ return String(val(s) || '') !== ''; })) return true;
        
        if (['top','right','bottom','left'].some(function(s){ var n = parseInt(val(s)); return !isNaN(n) && n > 0; })) return true;
        if (['top_c','right_c','bottom_c','left_c'].some(function(s){ return String(val(s) || '') !== ''; })) return true;
        return false;
    }

    return {
        register: register,
        getConfigForElement: getConfigForElement,
        renderHiddenInputs: function(prefix, settings) {

            return renderHiddenInputs(prefix, settings)
                + '<button type="button" class="impulse-crop-toggle" style="width:100%;height:26px;margin-top:8px;font-size:11px;background:#26292e;border:1px solid #3a3f45;border-radius:3px;color:#e0e0e0;font-family:inherit;cursor:pointer;transition:background 0.15s ease-in-out,color 0.15s ease-in-out">Crop</button>';
        },
        hasCropApplied: hasCropApplied,
        SUFFIXES: ALL_SUFFIXES
    };
})();

ImpulseCropBridge.register('image', {
    keyPrefix:    'image_crop_',
    radiusPrefix: 'image_radius_',
    extraFields:  ['image_radius_tl', 'image_radius_tr', 'image_radius_br', 'image_radius_bl']
});
ImpulseCropBridge.register('video', {
    keyPrefix:    'video_crop_',
    radiusPrefix: 'video_radius_',
    extraFields:  ['video_radius_tl', 'video_radius_tr', 'video_radius_br', 'video_radius_bl']
});

(function(){
    function sufx(){
        return (window.impulseDevice && window.impulseDevice !== 'desktop')
            ? '_' + window.impulseDevice : '';
    }
    function rd(n){ return jQuery('input[name="' + n + '"]').val() || ''; }
    function wr(n, v){ var $i = jQuery('input[name="' + n + '"]'); if ($i.length) $i.val(v); }

    function buildCropPayload(id) {
        var s = sufx();

        
        var cfg = ImpulseCropBridge.getConfigForElement(id) || { keyPrefix: 'image_crop_' };
        var P = cfg.keyPrefix;
        return {
            type: 'impulse-image-crop-enter',
            id:   id,
            oldT: rd(P + 'top' + s),
            oldR: rd(P + 'right' + s),
            oldB: rd(P + 'bottom' + s),
            oldL: rd(P + 'left' + s),
            tl: rd(P + 'tl' + s), tr: rd(P + 'tr' + s),
            br: rd(P + 'br' + s), bl: rd(P + 'bl' + s),
            rTL: rd((cfg.radiusPrefix || 'image_radius_') + 'tl' + s) || 0,
            rTR: rd((cfg.radiusPrefix || 'image_radius_') + 'tr' + s) || 0,
            rBR: rd((cfg.radiusPrefix || 'image_radius_') + 'br' + s) || 0,
            rBL: rd((cfg.radiusPrefix || 'image_radius_') + 'bl' + s) || 0,
            oldTopC: rd(P + 'top_c' + s), oldRightC: rd(P + 'right_c' + s),
            oldBottomC: rd(P + 'bottom_c' + s), oldLeftC: rd(P + 'left_c' + s),
            tC1: rd(P + 'top_c1' + s),    tC2: rd(P + 'top_c2' + s),
            rC1: rd(P + 'right_c1' + s),  rC2: rd(P + 'right_c2' + s),
            bC1: rd(P + 'bottom_c1' + s), bC2: rd(P + 'bottom_c2' + s),
            lC1: rd(P + 'left_c1' + s),   lC2: rd(P + 'left_c2' + s),
            
            topNodes:    rd(P + 'top_nodes' + s),
            rightNodes:  rd(P + 'right_nodes' + s),
            bottomNodes: rd(P + 'bottom_nodes' + s),
            leftNodes:   rd(P + 'left_nodes' + s),
            
            tlTangent:   rd(P + 'tl_tangent' + s),
            trTangent:   rd(P + 'tr_tangent' + s),
            brTangent:   rd(P + 'br_tangent' + s),
            blTangent:   rd(P + 'bl_tangent' + s)
        };
    }
    function postToFrame(m) {
        var ifr = document.getElementById('impulse-iframe');
        if (ifr && ifr.contentWindow) ifr.contentWindow.postMessage(m, '*');
    }

    

    var _cropLastId = null;
    var _cropAuthSent = false;  

    
    var _cropWanted = false;
    jQuery(document).on('click', '.impulse-crop-toggle', function(){
        _cropWanted = !_cropWanted;
        var $b = jQuery('.impulse-crop-toggle');
        if (_cropWanted) {
            $b.css({ background: '#fff', color: '#1d2327', borderColor: '#fff' });
            _cropAuthSent = false; 
        } else {
            $b.css({ background: '#26292e', color: '#e0e0e0', borderColor: '#3a3f45' });
            postToFrame({ type: 'impulse-image-crop-exit-cmd' });
        }
    });

    
    
    jQuery(document).on('click', '.impulse-img-cutout-btn', function() {

        if (!window.Impulse || !Impulse.isStandalone) { return; }
        var $btn = jQuery(this);
        var $flag = jQuery('input[name="use_cutout"]');
        var _cutDepthUi = function(cutOn) {
            jQuery('.impulse-img-depth-wrap').toggle(!cutOn);
            jQuery('.impulse-img-depth-offmsg').toggle(cutOn);
            jQuery('.impulse-cutout-depth-note').toggle(!cutOn);
        };
        if ($flag.val() === '1') {
            $flag.val('0');
            $btn.text('Remove background');
            _cutDepthUi(false);
            if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview(true);
            return;
        }
        var imageId = parseInt(jQuery('input[name="image_id"]').val()) || 0;
        if (!imageId) return;
        var imgSrc = jQuery('input[name="image_src"]').val() || '';
        $btn.text('Processing...').css('pointer-events', 'none');
        jQuery.ajax({
            url: ((window.Impulse && Impulse.siteUrl) || '') + '/api/cutout.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ image_id: imageId, image_url: imgSrc }),
            timeout: 300000
        }).done(function(resp) {
            var $msg = jQuery('.impulse-cutout-msg');
            if (resp && resp.success) {
                $flag.val('1');
                $btn.text('Restore background').css('pointer-events', '');
                $msg.hide().text('');
                _cutDepthUi(true);
                if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview(true);
            } else {
                $btn.text('Failed, try again').css('pointer-events', '');
                $msg.text((resp && resp.error) || 'The service could not process this image.').show();
            }
        }).fail(function(xhr) {
            $btn.text('Failed, try again').css('pointer-events', '');
            var d = null;
            try { d = JSON.parse(xhr.responseText); } catch (e) {}
            jQuery('.impulse-cutout-msg').text((d && d.error) || 'The service could not be reached.').show();
        });
    });
    setInterval(function(){
        var id = parseInt(jQuery('.impulse-panel-right').data('element-id')) || 0;
        var ifr = document.getElementById('impulse-iframe');
        var doc = ifr && ifr.contentDocument;
        
        var cfg = id ? ImpulseCropBridge.getConfigForElement(id) : null;
        var elIsCrop = !!cfg;
        var changed = (id !== _cropLastId);
        if (changed) {
            if (_cropLastId) postToFrame({ type: 'impulse-image-crop-exit-cmd' });
            _cropLastId = id;
            _cropAuthSent = false;  
            _cropWanted = false;    
        }
        if (id && elIsCrop && _cropWanted) {

            

            

            

            

            
            
            if (doc && !doc.querySelector('.impulse-crop-overlay') && !_cropAuthSent) {

                

                

                

                

                

                

                var s = sufx();
                var P = cfg.keyPrefix;
                var $tl = jQuery('input[name="' + P + 'tl' + s + '"]');
                if ($tl.length) {
                    postToFrame(buildCropPayload(id));
                    _cropAuthSent = true;
                }

            }
        }
    }, 30); 

            

    jQuery(document).on('click', '.impulse-image-crop-reset-btn', function(e){
        e.preventDefault();
        var sfx = (typeof sufx === 'function') ? sufx() : '';
        ['top','right','bottom','left'].forEach(function(side) {
            jQuery('input[name="image_crop_' + side + '_nodes' + sfx + '"]').val('');
        });
        postToFrame({ type: 'impulse-image-crop-reset' });

        
        jQuery(this).hide();
        if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview(true);
    });

    
    function _parseXY(v) {
        if (typeof v !== 'string' || v.indexOf(',') < 0) return null;
        var p = v.split(',').map(parseFloat);
        return (p.length === 2 && isFinite(p[0]) && isFinite(p[1])) ? p : null;
    }
    jQuery(document).on('click', '.impulse-image-add-node-btn', function(e){
        e.preventDefault();
        var side = jQuery(this).attr('data-side');
        var tl = _parseXY(jQuery('input[name="image_crop_tl"]').val()) || [0,0];
        var tr = _parseXY(jQuery('input[name="image_crop_tr"]').val()) || [100,0];
        var br = _parseXY(jQuery('input[name="image_crop_br"]').val()) || [100,100];
        var bl = _parseXY(jQuery('input[name="image_crop_bl"]').val()) || [0,100];
        var A, B;
        if (side === 'top')         { A = tl; B = tr; }
        else if (side === 'right')  { A = tr; B = br; }
        else if (side === 'bottom') { A = br; B = bl; }
        else                        { A = bl; B = tl; }
        var $in = jQuery('input[name="image_crop_' + side + '_nodes"]');
        var raw = $in.val() || '';
        var nodes = [];
        try { var parsed = raw ? JSON.parse(raw) : []; if (Array.isArray(parsed)) nodes = parsed; } catch (e2) {}

        var t = (nodes.length + 1) / (nodes.length + 2);
        var midX = A[0] + (B[0] - A[0]) * t;
        var midY = A[1] + (B[1] - A[1]) * t;
        var dx = B[0] - A[0], dy = B[1] - A[1];
        var len = Math.sqrt(dx*dx + dy*dy) || 1;
        var nx = -dy / len, ny = dx / len;
        var off = 12;
        nodes.push({
            x: Math.max(0, Math.min(100, midX + nx * off)),
            y: Math.max(0, Math.min(100, midY + ny * off))
        });
        $in.val(JSON.stringify(nodes));
        if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
    });

    

    

    window.addEventListener('message', function(e){
        if (!e || !e.data) return;
        if (e.data.type === 'impulse-image-crop-commit') {
            var s = sufx();
            
            var _id = parseInt(jQuery('.impulse-panel-right').data('element-id')) || 0;
            var _cfg = ImpulseCropBridge.getConfigForElement(_id) || { keyPrefix: 'image_crop_' };
            var P = _cfg.keyPrefix;
            wr(P + 'tl' + s, e.data.tl || '');
            wr(P + 'tr' + s, e.data.tr || '');
            wr(P + 'br' + s, e.data.br || '');
            wr(P + 'bl' + s, e.data.bl || '');
            wr(P + 'top_c1' + s,    e.data.tC1 || '');
            wr(P + 'top_c2' + s,    e.data.tC2 || '');
            wr(P + 'right_c1' + s,  e.data.rC1 || '');
            wr(P + 'right_c2' + s,  e.data.rC2 || '');
            wr(P + 'bottom_c1' + s, e.data.bC1 || '');
            wr(P + 'bottom_c2' + s, e.data.bC2 || '');
            wr(P + 'left_c1' + s,   e.data.lC1 || '');
            wr(P + 'left_c2' + s,   e.data.lC2 || '');
            wr(P + 'top_nodes' + s,    e.data.topNodes    || '');
            wr(P + 'right_nodes' + s,  e.data.rightNodes  || '');
            wr(P + 'bottom_nodes' + s, e.data.bottomNodes || '');
            wr(P + 'left_nodes' + s,   e.data.leftNodes   || '');
            wr(P + 'tl_tangent' + s, e.data.tlTangent || '');
            wr(P + 'tr_tangent' + s, e.data.trTangent || '');
            wr(P + 'br_tangent' + s, e.data.brTangent || '');
            wr(P + 'bl_tangent' + s, e.data.blTangent || '');

            

            

            var RP = _cfg.radiusPrefix || 'image_radius_';
            wr(RP + 'tl' + s, Math.round(parseFloat(e.data.rTL) || 0));
            wr(RP + 'tr' + s, Math.round(parseFloat(e.data.rTR) || 0));
            wr(RP + 'br' + s, Math.round(parseFloat(e.data.rBR) || 0));
            wr(RP + 'bl' + s, Math.round(parseFloat(e.data.rBL) || 0));
            
            wr(P + 'top' + s, 0);
            wr(P + 'right' + s, 0);
            wr(P + 'bottom' + s, 0);
            wr(P + 'left' + s, 0);
            wr(P + 'top_c' + s, '');
            wr(P + 'right_c' + s, '');
            wr(P + 'bottom_c' + s, '');
            wr(P + 'left_c' + s, '');

            jQuery('.impulse-image-crop-reset-btn').show();

            

            

            try {
                var id = jQuery('.impulse-panel-right').data('element-id');
                if (id) {

                    

                    

                    
                    var patch = {};

                    var fields = ImpulseCropBridge.SUFFIXES.map(function(suf){ return P + suf; });
                    if (_cfg.extraFields) {
                        fields = fields.concat(_cfg.extraFields);
                    }
                    var dvc = s; 
                    for (var fi = 0; fi < fields.length; fi++) {
                        var fname = fields[fi] + dvc;
                        var $i = jQuery('input[name="' + fname + '"]');
                        if (!$i.length) continue;
                        patch[fname] = $i.val();
                    }

                    var existingCache = jQuery('.impulse-panel-right').data('existing-settings') || {};
                    jQuery('.impulse-panel-right').data('existing-settings',
                        jQuery.extend({}, existingCache, patch));
                    jQuery.ajax({
                        url: Impulse.api + 'elements/' + id,
                        method: 'PUT',
                        headers: { 'X-WP-Nonce': Impulse.nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ settings: patch, page_id: Impulse.pageId })
                    });
                }
            } catch (_e) {}
        }
    });

    jQuery(document).on('change', 'input[name="image_pin_to_screen"]', function(){
        var on = jQuery(this).is(':checked');
        jQuery('.impulse-image-flow-only').toggle(!on);
    });

    
    
    jQuery(document).on('click', '.impulse-image-shadow-side-btn', function(e){
        e.preventDefault();
        var $btn = jQuery(this);
        var side = $btn.attr('data-side');
        var nextActive = !$btn.hasClass('active');
        $btn.toggleClass('active', nextActive);
        jQuery('input[name="image_shadow_' + side + '"]').val(nextActive ? '1' : '0');
        if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview();
    });

    

})();

(function(){
    jQuery(document).on('click', '.impulse-align-dot[data-target="image"]', function(e){
        e.stopPropagation();
        var $dot = jQuery(this);
        var ha = $dot.data('ca') || 'center';
        var va = $dot.data('va') || 'center';
        var sfx = (window.impulseDevice && window.impulseDevice !== 'desktop')
            ? '_' + window.impulseDevice : '';
        jQuery('input[name="image_h_align' + sfx + '"]').val(ha);
        jQuery('input[name="image_v_align' + sfx + '"]').val(va);
        
        jQuery('.impulse-align-dot[data-target="image"]').removeClass('active');
        $dot.addClass('active');
        
        var id = jQuery('.impulse-panel-right').data('element-id');
        var iframe = document.getElementById('impulse-iframe');
        var doc = iframe && iframe.contentDocument;
        if (doc && id) {
            var w = doc.querySelector('.impulse-el[data-id="' + id + '"] .impulse-image-wrapper.impulse-image-pinned');
            if (w) {
                w.style.top = ''; w.style.bottom = '';
                w.style.left = ''; w.style.right = '';
                if (va === 'top')         w.style.top = '0';
                else if (va === 'bottom') w.style.bottom = '0';
                else                       w.style.top = '50%';
                if (ha === 'left')         w.style.left = '0';
                else if (ha === 'right')   w.style.right = '0';
                else                        w.style.left = '50%';
                var offX = parseFloat(jQuery('input[name="image_offset_x' + sfx + '"]').val()) || 0;
                var offY = parseFloat(jQuery('input[name="image_offset_y' + sfx + '"]').val()) || 0;

                
                var cx = (ha === 'center') ? '-50%' : '0vw';
                var cy = (va === 'center') ? '-50%' : '0vh';
                w.style.transform = 'translate(calc(' + cx + ' + ' + offX + 'vw), calc(' + cy + ' + ' + offY + 'vh))';
            }
        }
        
        if (typeof autoSaveAndPreview === 'function') autoSaveAndPreview(false);
    });
})();
