(function($) {
    'use strict';
    
    var ajaxurl = window.Impulse?.ajaxUrl || window.ajaxurl || '';
    var dashboardInitialized = false;
    var currentSection = 'orders';
    var currentSettingsTab = 'general';
    var teamLoaded = false;

    function impulseAutoExpand(el) {
        el.style.height = '26px';
        el.style.height = Math.max(26, el.scrollHeight) + 'px';
    }
    $(document).on('input', '.impulse-autoexpand', function() { impulseAutoExpand(this); });

    $(document).on('click', '.impulse-pw-toggle', function() {
        var $input = $(this).siblings('.impulse-pw-field');
        var isHidden = $input.attr('type') === 'password';
        $input.attr('type', isHidden ? 'text' : 'password');
        $(this).css('color', isHidden ? '#e0e0e0' : '#555');
    });
    var volumeLoaded = false;
    var currenciesLoaded = false;
    var loyaltyLoaded = false;
    var gcLoaded = false;
    var recLoaded = false;
    var currentStatusFilter = 'all';
    var selectedItemId = null;
    var selectedItemType = null;

    function showToast(message, type) {
        type = type || 'success';
        var $toast = $('<div class="impulse-toast impulse-toast-' + type + '">' + escapeHtml(message) + '</div>');
        $('body').append($toast);
        setTimeout(function() { $toast.addClass('show'); }, 10);
        setTimeout(function() { $toast.removeClass('show'); }, 3000);
        setTimeout(function() { $toast.remove(); }, 3500);
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    $(document).on('impulse:workspace:store', function() {
        initDashboardWorkspace();
        
        $('#impulse-store-nav').show();
        $('.impulse-store-grid').removeClass('settings-active');

        
        
        var target = (window.Impulse && window.Impulse._storeSectionOverride) || 'orders';
        if (window.Impulse) { window.Impulse._storeSectionOverride = null; }
        if (typeof switchStoreSection === 'function') switchStoreSection(target);
    });

    $(document).on('impulse:workspace:settings', function() {
        initDashboardWorkspace();
        
        $('#impulse-store-nav').hide();
        $('.impulse-store-grid').addClass('settings-active');
        switchStoreSection('settings');
    });

    $(document).ready(function() {
        if (window.Impulse && (window.Impulse.workspace === 'store' || window.Impulse.workspace === 'settings')) {
            initDashboardWorkspace();
            if (window.Impulse.workspace === 'settings') {
                $('#impulse-store-nav').hide();
                $('.impulse-store-grid').addClass('settings-active');
                switchStoreSection('settings');
            }
        }
    });
    
    function initDashboardWorkspace() {
        if (dashboardInitialized) return;
        dashboardInitialized = true;
        
        bindSectionSwitching();
        bindSettingsTabSwitching();
        bindStatusFilters();
        bindItemSelection();
        bindSearch();
        bindActionButtons();

        switchStoreSection(Impulse.storeSectionDefault || 'orders');
    }

    function storeRightCollapse() {
        
        if (currentSection === 'settings') return;
        if ($('.impulse-editor').attr('data-workspace') === 'settings') return;
        var $grid = $('.impulse-store-grid');
        var $panel = $grid.find('.impulse-panel-right');
        if ($grid.hasClass('right-collapsed')) return;
        
        $panel.css({ transition: 'transform 0.22s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.18s ease-in-out', transform: 'translateX(100%)', opacity: '0' });
        setTimeout(function() {
            $grid.addClass('right-collapsed');
            $panel.css({ transform: '', opacity: '', transition: '' });
        }, 220);
    }
    function storeRightExpand() {
        var $grid = $('.impulse-store-grid');
        var $panel = $grid.find('.impulse-panel-right');
        if (!$grid.hasClass('right-collapsed')) return;
        
        $grid.removeClass('right-collapsed');
        $panel.css({ transform: 'translateX(100%)', opacity: '0', transition: 'none' });
        requestAnimationFrame(function() {
            requestAnimationFrame(function() {
                $panel.css({ transition: 'transform 0.22s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.18s ease-in-out', transform: 'translateX(0)', opacity: '1' });
                setTimeout(function() { $panel.css({ transform: '', opacity: '', transition: '' }); }, 240);
            });
        });
    }
    window.storeRightExpand = storeRightExpand;

    function switchStoreSection(section) {
        currentSection = section;
        
        if (section === 'settings' || section === 'bookings') {
            storeRightExpand();
        } else {
            storeRightCollapse();
        }
        
        $('[data-workspace="store"] .impulse-store-nav-btn[data-store-section]').removeClass('active');
        if (section !== 'settings') {
            $('[data-workspace="store"] .impulse-store-nav-btn[data-store-section="' + section + '"]').addClass('active');
        }
        
        $('#products-cats-panel').hide();
        $('#orders-status-panel').hide();
        $('[data-workspace="store"] .impulse-store-left-content').hide();
        $('[data-workspace="store"] .impulse-store-left-content[data-section="' + section + '"]').show();
        $('[data-workspace="store"] .impulse-store-section').hide();
        $('[data-workspace="store"] .impulse-store-section[data-section="' + section + '"]').show();
        $('[data-workspace="store"] .impulse-store-right-content').hide();
        $('[data-workspace="store"] .impulse-store-right-content[data-section="' + section + '"]').show();
        
        if (section === 'bookings') {
            if (!bookingsState.initialized) {
                bookingsState.initialized = true;
                initBookingsCalendar();
                loadBookingsList();
                loadAllBookingDates();
                loadServicesListData();
                loadBookingsStats();
            }
        }
        
        if (section === 'inquiries') {
            if (!inquiriesState.loaded) { inquiriesState.loaded = true; loadInquiries(); }
        }

        
        if (section === 'staff') { if (!staffState.loaded) { loadStaffListData(); } }
        
        if (section === 'bookings') { if (!staffState.loaded) { loadStaffListData(); } }
        
        if (section === 'products') {
            
            $('[data-workspace="store"] .impulse-store-right-content').hide();
            $('[data-workspace="store"] .impulse-store-right-content[data-section="products"]').show();
            $('#impulse-products-edit').html('');
            setProductsRightTitle('');
        }
        
        $('#topbar-add-product').toggle(section === 'products');
        $('#topbar-add-service').toggle(section === 'bookings');
        $('#topbar-add-booking').toggle(section === 'bookings');
        $('#feature-status-panel').hide();
        $('.impulse-feature-tile').removeClass('selected');
        $('.impulse-feature-toggle').removeClass('active-nav');
        $('.impulse-all-nav-item').removeClass('active');
        $('[data-settings="__placeholder"]').remove();
        
        if (section !== 'orders' && ordersTabMode !== 'orders') {
            setOrdersTabMode('orders');
        }
        
        if (section !== 'products' && productsTabMode !== 'products') {
            productsTabMode = 'products'; 
            $('#products-mode-products').addClass('active');
            $('#products-mode-bundles').removeClass('active');
        }
        if (section !== 'settings') showSectionView(section, 'tiles');
        if (section === 'settings') {
            
            if (!currenciesLoaded) { currenciesLoaded = true; loadCurrencies(); }
            if (!teamLoaded) { teamLoaded = true; loadTeamData(); }
            if (!shippingAfterShipLoaded) { shippingAfterShipLoaded = true; loadShippingAfterShip(); }
            
            setTimeout(function() {
                $('.impulse-autoexpand').each(function() { impulseAutoExpand(this); });
            }, 0);
            
            currentSettingsTab = null;
            switchSettingsTab('general');
            
            $('[data-workspace="store"] .impulse-store-right-content').hide();
            $('[data-workspace="store"] .impulse-store-right-content[data-section="settings"]').show();
            $('#feature-status-panel').hide();
            $('#settings-email-panel').show();
            $('#settings-support-panel').show();
            $('#settings-detail-content').hide();
            renderEmailsRightPanel();
        } else if (section !== 'settings') {
            $('#settings-detail-content').hide();
        }
    }

    function showSectionView(section, view) {
        if (section === 'products') {
            $('.impulse-all-nav-item[data-section="products"]').removeClass('active');
            var $pbar = $('#products-bar-card');
            var alreadyExpanded = $pbar.hasClass('expanded');
            if (!alreadyExpanded) {
                $pbar.addClass('expanded');
            }
            if (productsTabMode === 'products') {
                $('#products-cats-panel').show();
                $(document).trigger('impulse:products:show');
            } else {
                
                $('#products-tab-content').hide();
                $('#bundles-center-list').show();
                $('#bundles-toolbar-extra').show();
                $('#products-cats-panel').hide();
            }
            return;
        }
        if (section === 'orders') {
            $('#orders-status-panel').show();

            
            
            if (window.Impulse && window.Impulse.storeType === 'memberships') {
                setOrdersTabMode('clients');
            }
            return;
        }
        if (section === 'customers') {
            
            switchStoreSection('orders');
            setOrdersTabMode('clients');
            return;
        }
        var $section = $('[data-workspace="store"] .impulse-store-section[data-section="' + section + '"]');
        $section.find('.impulse-section-view').hide();
        $section.find('.impulse-section-view[data-view="' + view + '"]').css('display', 'flex');
        $('.impulse-all-nav-item[data-section="' + section + '"]').toggleClass('active', view === 'list');
        if (view === 'tiles') {
            renderFeatureTiles(section);
        } else {
            $('.impulse-feature-tile').removeClass('selected');
            $('#feature-status-panel').hide();
            $('[data-workspace="store"] .impulse-store-right-content').hide();
            $('[data-workspace="store"] .impulse-store-right-content[data-section="' + section + '"]').show();
        }
    }

    function isAddonActive(key) {
        return true; 
    }

    var featureRegistry = {};

    var _featureGridSortable = {};
    var DRAG_HANDLE = '<span class="impulse-feature-card-drag"><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>';

    function getFeatureOrder(section) {
        try {
            var saved = localStorage.getItem('impulse_feat_order_' + section);
            return saved ? JSON.parse(saved) : null;
        } catch(e) { return null; }
    }
    function saveFeatureOrder(section) {
        var keys = [];
        $('#' + section + '-feature-grid .impulse-feature-card[data-feature]').each(function() {
            keys.push($(this).data('feature'));
        });
        try { localStorage.setItem('impulse_feat_order_' + section, JSON.stringify(keys)); } catch(e) {}
    }

    function renderFeatureCards(section) {
        var features = featureRegistry[section] || [];
        var storeType = window.Impulse.storeType || 'mixed';
        var $grid = $('#' + section + '-feature-grid');
        var activeHtml = '';

        var savedOrder = getFeatureOrder(section);
        if (savedOrder && savedOrder.length) {
            var ordered = [];
            var keyMap = {};
            features.forEach(function(f) { keyMap[f.key] = f; });
            savedOrder.forEach(function(k) { if (keyMap[k]) ordered.push(keyMap[k]); });
            
            features.forEach(function(f) { if (savedOrder.indexOf(f.key) === -1) ordered.push(f); });
            features = ordered;
        }

        features.forEach(function(f) {
            if (f.key === 'products' || f.key === 'orders' || f.key === 'customers') return; 
            if (f.storeTypes && f.storeTypes.indexOf(storeType) === -1) return;
            var isCrudCard = ['bundles','product_addons','coupons','gift_cards'].indexOf(f.key) !== -1;
            activeHtml += '<div class="impulse-feature-card" data-feature="' + f.key + '" data-section="' + section + '">';
            activeHtml += '<div class="impulse-feature-card-header">';
            activeHtml += DRAG_HANDLE;
            activeHtml += '<span class="impulse-feature-card-name">' + f.label + '</span>';
            if (isCrudCard) {
                activeHtml += '<button type="button" class="impulse-btn-sm impulse-card-add-btn" data-feature="' + f.key + '" style="height:22px;padding:0 8px;font-size:10px;flex-shrink:0">+ Add</button>';
            }
            activeHtml += '</div>';
            activeHtml += '<div class="impulse-feature-card-body" id="card-body-' + f.key + '">';
            activeHtml += '<div style="font-size:11px;color:#888">Loading...</div>';
            activeHtml += '</div>';
            activeHtml += '</div>';
        });

        var html = activeHtml || '<div style="text-align:center;padding:40px 0;color:#777;font-size:11px">No features available for this store type.</div>';

        $grid.html(html);

        if (typeof Sortable !== 'undefined') {
            if (_featureGridSortable[section]) { try { _featureGridSortable[section].destroy(); } catch(e) {} }
            _featureGridSortable[section] = new Sortable($grid[0], {
                animation: 150,
                ghostClass: 'sortable-ghost',
                handle: '.impulse-feature-card-drag',
                filter: '.impulse-feature-tile,.impulse-section-divider',
                onEnd: function() { saveFeatureOrder(section); }
            });
        }

        (featureRegistry[section] || []).forEach(function(f) {
            var cfg = featureStatusConfig[f.key];
            if (cfg && cfg.loadCardStats) cfg.loadCardStats(f.key);
        });
    }

    function renderFeatureTiles(section) { renderFeatureCards(section); }

    function expandFeatureCard(key, section) {
        
        if (key === 'products') {
            var $card = $('#products-bar-card');
            var wasExpanded = $card.hasClass('expanded');
            $('.impulse-feature-card').removeClass('expanded');
            if (!wasExpanded) {
                $card.addClass('expanded');
                $('#products-cats-panel').show();
                if (!productsState.initialized) $(document).trigger('impulse:store:products');
            } else {
                $('#products-cats-panel').hide();
            }
            return;
        }

        var $card = $('.impulse-feature-card[data-feature="' + key + '"]');
        if (!$card.length) return;
        var isExpanded = $card.hasClass('expanded');
        var isCrudCard = ['bundles','product_addons','coupons','gift_cards'].indexOf(key) !== -1;

        $('.impulse-feature-card').removeClass('expanded');

        $('#orders-status-panel').hide();

        if (isExpanded) {
            $('#feature-status-panel').hide();
            if (isCrudCard) {
                $('[data-workspace="store"] .impulse-store-right-content').hide();
                $('[data-workspace="store"] .impulse-store-right-content[data-section="' + section + '"]').show();
                $('#impulse-products-edit').html('');
                setProductsRightTitle('');
            }
            return;
        }

        $card.addClass('expanded');
        selectTile(key, section);

        if (!isCrudCard) {
            $('#impulse-products-edit').html('');
            setProductsRightTitle('');
        }

        if (isCrudCard) {
            openCrudRightPanel(key, null);
        }

        var $body = $card.find('.impulse-feature-card-body');
        if (!$body.data('loaded')) {
            $body.data('loaded', true);
            loadFeatureCardContent(key, $body.attr('id'));
        }
    }

    function loadFeatureCardContent(key, containerId) {
        if (key === 'bundles')          { loadBundlesCard(containerId); return; }
        if (key === 'product_addons')   { loadProductAddonsCard(containerId); return; }
        if (key === 'volume_discounts') { loadVolumeDiscountsCard(containerId); return; }
        if (key === 'coupons')          { loadCouponsCard(containerId); return; }
        if (key === 'loyalty')          { loadLoyaltyCard(containerId); return; }
        if (key === 'gift_cards')       { loadGiftCardsCard(containerId); return; }
        $('#' + containerId).html('<div style="font-size:11px;color:#555;padding:24px;text-align:center">Settings coming soon.</div>');
    }

    function isAddonActive(key) {
        return true; 
    }

    function selectTile(key, section) {
        
        $('[data-workspace="store"] .impulse-store-right-content').hide();
        $('[data-workspace="store"] .impulse-store-right-content[data-section="settings"]').show();

        var cfg = featureStatusConfig[key];
        if (cfg) {
            showFeatureStatusPanel(key);
        } else {
            var featureName = '';
            var allFeatures = [].concat(featureRegistry.products||[]);
            for (var i = 0; i < allFeatures.length; i++) {
                if (allFeatures[i].key === key) { featureName = allFeatures[i].label; break; }
            }
            $('#feature-status-panel').attr('data-feature', key).show();
            $('#feature-status-name').text(featureName);
            $('#feature-stats-grid').html('<div style="grid-column:span 2;padding:12px 0;color:#555;font-size:11px">Settings panel coming soon</div>');
            $('#feature-autosave-indicator').css('opacity', 0);
        }
    }

    function openFeaturePanel(key, source) {
        $('[data-settings="__placeholder"]').remove();
        var $panel = $('[data-workspace="store"] .impulse-settings-panel[data-settings="' + key + '"]');
        if (!$panel.length) return;
        $('.impulse-feature-card').removeClass('expanded');
        $('[data-workspace="store"] .impulse-store-left-content').hide();
        $('[data-workspace="store"] .impulse-store-section').hide();
        $('[data-workspace="store"] .impulse-store-section[data-section="settings"]').show();
        $('[data-workspace="store"] .impulse-store-right-content').hide();
        $('[data-workspace="store"] .impulse-store-right-content[data-section="settings"]').show();
        $('.impulse-store-grid').addClass('settings-active');
        $('#impulse-store-nav').hide();
        
        $('[data-workspace="store"] .impulse-settings-panel').hide();
        $panel.show();
        $('#impulse-products-edit').html('');
        setProductsRightTitle('');
        currentSettingsTab = key;
        currentSection = source;
        showFeatureStatusPanel(key);
    }

    

    

    function bindSectionSwitching() {
        $('[data-workspace="store"] .impulse-store-nav-btn[data-store-section]').on('click', function() {
            var section = $(this).data('store-section');
            switchStoreSection(section);
        });

        $(document).on('click', '.impulse-all-nav-item', function() {
            var section = $(this).data('section');
            showSectionView(section, 'list');
        });

        $(document).on('click', '.impulse-feature-card-header', function(e) {
            
            if ($(e.target).closest('.impulse-feature-card-drag, button').length) return;
            var $card = $(this).closest('.impulse-feature-card');
            var key    = $card.data('feature');
            var source = $card.data('section');
            expandFeatureCard(key, source);
        });

    }

    var CORE_SETTINGS_TABS = ['general', 'payments', 'emails'];

    function switchSettingsTab(tab) {
        if (tab === currentSettingsTab) return;
        currentSettingsTab = tab;

        $('[data-workspace="store"] .impulse-store-right-content').hide();
        $('[data-workspace="store"] .impulse-store-right-content[data-section="settings"]').show();

        var isCore = CORE_SETTINGS_TABS.indexOf(tab) !== -1;

        $('[data-workspace="store"] .impulse-settings-panel').hide();
        if (!isCore) {
            $('[data-workspace="store"] .impulse-settings-panel[data-settings="' + tab + '"]').show();
        }

        if (isCore) {
            $('#settings-email-panel').show();
            $('#settings-support-panel').show();
            $('#feature-status-panel').hide();
            $('#settings-detail-content').hide();
            renderEmailsRightPanel();
        } else {
            $('#settings-email-panel').hide();
            $('#settings-support-panel').hide();
        }

        if (!window._settingsSeoRendered) {
            window._settingsSeoRendered = true;
            if (window._seoState && !window._seoState.settings && typeof window.seoLoadSettings === 'function') window.seoLoadSettings();
            if (window._seoState && window._seoState.settings && typeof window.seoRenderSettingsCenter === 'function') { window.seoRenderSettingsCenter(); window.seoRenderSettingsLeft(); }
        }

        if (tab === 'volume_discounts' && !volumeLoaded) { volumeLoaded = true; loadVolumeTiers(); }
        if (tab === 'coupons') { loadCouponList(); }
        if (tab === 'loyalty' && !loyaltyLoaded) { loyaltyLoaded = true; loadLoyaltySettings(); }
        if (tab === 'gift_cards' && !gcLoaded) { gcLoaded = true; loadGiftCards(); }

        if (typeof window.upgradeCheckboxes === 'function') {
            var _sPanel = isCore
                ? document.querySelector('.impulse-store-grid')
                : document.querySelector('.impulse-settings-panel[data-settings="' + tab + '"]');
            if (_sPanel) window.upgradeCheckboxes(_sPanel);
        }
    }

    $(document).on('click', '#paypal-sandbox-toggle', function() {
        var $btn = $(this);
        var $val = $('#paypal-sandbox-val');
        var isSandbox = $btn.data('value') === '1' || $btn.data('value') === 1;
        var newSandbox = !isSandbox;

        $btn.data('value', newSandbox ? '1' : '0');
        $val.val(newSandbox ? '1' : '0');

        if (newSandbox) {
            $btn.text('Sandbox').css({'background':'#2a2e33','border-color':'#3a3f44','color':'#888'});
        } else {
            $btn.text('Live').css({'background':'#2a2e33','border-color':'#3a3f44','color':'#e0e0e0'});
        }
        
        $val.trigger('change');
    });

    
    $(document).on('click', '.inst-onoff-toggle', function() {
        var $btn = $(this);
        var $val = $('#' + $btn.data('target'));
        var on = !($btn.data('value') === '1' || $btn.data('value') === 1);
        $btn.data('value', on ? '1' : '0');
        $val.val(on ? '1' : '0');
        $btn.text(on ? 'On' : 'Off').css('color', on ? '#e0e0e0' : '#888');
        $val.trigger('change');
    });

    $(document).on('click', '#authorizenet-sandbox-toggle', function() {
        var $btn = $(this);
        var $val = $('#authorizenet-sandbox-val');
        var isSandbox = $btn.data('value') === '1' || $btn.data('value') === 1;
        var newSandbox = !isSandbox;

        $btn.data('value', newSandbox ? '1' : '0');
        $val.val(newSandbox ? '1' : '0');

        if (newSandbox) {
            $btn.text('Sandbox').css({'background':'#2a2e33','border-color':'#3a3f44','color':'#888'});
        } else {
            $btn.text('Live').css({'background':'#2a2e33','border-color':'#3a3f44','color':'#e0e0e0'});
        }
        $val.trigger('change');
    });

    function bindSettingsTabSwitching() {

        $('#settings-tabs .impulse-list-item[data-settings-tab]').on('click', function() {
            switchSettingsTab($(this).data('settings-tab'));
        });

        $(document).on('click', '[data-section="settings"] .impulse-store-left-bottom .impulse-btn-sm[data-settings-tab]', function() {
            switchSettingsTab($(this).data('settings-tab'));
        });

    }

    

    

    
    var PLATFORM = 'https://platform.instinctor.com';

    
    
    (function() {

        var licBilling = 'monthly';        
        var licPlan    = 'pro';            

        
        
        var licPricing = {
            tiers: {
                pro: {
                    name: 'Pro', sites_allowed: 1,
                    monthly_formatted: '$29.90/mo', annual_formatted: '$249/yr'
                },
                pro_studio: {
                    name: 'Pro Studio', sites_allowed: 5,
                    monthly_formatted: '$99/mo', annual_formatted: '$899/yr'
                }
            }
        };

        

        
        
        $.ajax({
            url: PLATFORM + '/api/pricing',
            dataType: 'json'
        }).done(function(resp) {
            if (!resp || !resp.success || !resp.pricing) return;
            if (resp.pricing.tiers && resp.pricing.tiers.pro) {
                licPricing = resp.pricing;
            } else if (resp.pricing.monthly_formatted) {
                licPricing.tiers.pro.monthly_formatted = resp.pricing.monthly_formatted;
                licPricing.tiers.pro.annual_formatted  = resp.pricing.annual_formatted;
            }
            updatePlanBillingLabels();
            updateUpgradeBtnLabel();
        }).fail(function() {

        });

        
        function updatePlanBillingLabels() {

        }

        $(document).on('click', '.impulse-notif-pro-badge', function() {
            triggerUpgradeCheckout();
        });

        $(document).on('click', '.impulse-notif-pro-badge[data-settings-tab]', function() {
            triggerUpgradeCheckout();
        });

        $(document).on('click', '#impulse-screen-bar [data-settings-tab="license"]', function() {
            switchStoreSection('settings');
            switchSettingsTab('license');
        });

        function unlockNotifRows() {
            ['sms', 'whatsapp'].forEach(function(type) {
                var $row = $('#notif-row-' + type);
                $row.removeClass('notif-pro-locked');
                $row.find('input').prop('disabled', false).css('color', '#e0e0e0').css('cursor', '');
                $row.find('input[type="checkbox"]').css('cursor', 'pointer');
                
                $row.find('.impulse-notif-pro-badge').replaceWith(
                    '<button type="button" class="impulse-btn-sm" id="impulse-chat-test-' + type + '" style="height:26px;padding:0 8px;font-size:10px;background:#2a2e33;border:none;border-left:1px solid #3a3f44;border-radius:0;color:#999;cursor:pointer;white-space:nowrap">Test</button>'
                );
            });
        }

        function renderLicStatus() {
            var tier  = window.Impulse.tier || 'free';
            var email = window.Impulse.licenseEmail || '';
            var labels = { pro: 'Pro', agency: 'Agency', free: 'Free', degraded: 'Degraded' };
            var label  = labels[tier] || (tier.charAt(0).toUpperCase() + tier.slice(1));

            $('#lic-tier-label').text(label).css('color', tier === 'degraded' ? '#888' : '#e0e0e0');
            $('#lic-email-label').text(email || '');

            
            
            if (window.Impulse.subscriptionActive) {
                $('#lic-upgrade-section').hide();
            } else {
                $('#lic-upgrade-section').show();
            }
        }

        
        
        function updateUpgradeBtnLabel() {
            var t        = (licPricing.tiers && licPricing.tiers[licPlan]) || {};
            var fmt      = (t.monthly_formatted || '$29.90').replace(/\/(yr|mo)$/, '');
            var planName = t.name || (licPlan === 'pro_studio' ? 'Pro Studio' : 'Pro');
            var verb     = (window.Impulse.tier && window.Impulse.tier !== 'free') ? 'Renew' : 'Get';
            $('#lic-upgrade-btn').html(
                '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg> ' + verb + ' '
                + planName + ' — ' + fmt + '/month'
            );
        }

        
        $(document).on('click', '.lic-plan-btn', function() {
            $('.lic-plan-btn').removeClass('active').css({ background: '#2a2e33', color: '#999', 'border-color': '#3a3f44' });
            $(this).addClass('active').css({ background: '#3a3f44', color: '#e0e0e0' });
            licPlan = $(this).data('plan');

            updatePlanBillingLabels();
            updateUpgradeBtnLabel();
        });

        $(document).on('click', '#lic-activate-btn', function() {
            var key = $('#lic-key-input').val().trim();
            if (!key) { $('#lic-activate-msg').text('Please enter a license key.').css('color', '#888'); return; }

            $('#lic-activate-btn').prop('disabled', true).text('Activating…');
            $('#lic-activate-msg').text('').css('color', '#555');

            $.post(window.Impulse.ajaxUrl, {
                action: 'instinctor_activate_license',
                nonce:  window.Impulse.adminNonce,
                license_key: key
            }, function(resp) {
                $('#lic-activate-btn').prop('disabled', false).text('Activate');
                if (resp && resp.success) {
                    var tier = resp.data.tier || 'pro';
                    window.Impulse.tier        = tier;
                    window.Impulse.isPro       = (tier === 'pro' || tier === 'agency');
                    window.Impulse.hasProLicense = (tier === 'pro' || tier === 'agency');
                    $('#lic-activate-msg').text('Activated — ' + (resp.data.tier_label || 'Pro')).css('color', '#e0e0e0');
                    $('#lic-key-input').val('');
                    renderLicStatus();
                    if (tier !== 'free') unlockNotifRows();
                } else {
                    var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Activation failed.';
                    $('#lic-activate-msg').text(msg).css('color', '#888');
                }
            }).fail(function() {
                $('#lic-activate-btn').prop('disabled', false).text('Activate');
                $('#lic-activate-msg').text('Connection error. Try again.').css('color', '#888');
            });
        });

        

        
        $(document).on('click', '#settings-backup-download', function() {
            var $btn = $('#settings-backup-download');
            var $msg = $('#settings-backup-msg');
            $btn.prop('disabled', true);
            var origHtml = $btn.html();
            $btn.text('Preparing…');
            $msg.text('').css('color', '#555');

            var restBase = (window.Impulse && window.Impulse.restUrl) ? window.Impulse.restUrl : '/api/instinctor/v1/';
            var url = restBase.replace(/\/+$/, '') + '/site/export';

            
            var headers = { 'Accept': 'application/json' };
            var nonce = (window.Impulse && window.Impulse.restNonce) ||
                        (window.wpApiSettings && window.wpApiSettings.nonce) || '';
            if (nonce) headers['X-WP-Nonce'] = nonce;

            fetch(url, { credentials: 'same-origin', headers: headers })
                .then(function(r){
                    if (!r.ok) throw new Error('HTTP ' + r.status);
                    return r.json();
                })
                .then(function(data){
                    var stamp = new Date().toISOString().slice(0, 10); 
                    var host  = (window.location.hostname || 'instinctor').replace(/[^a-z0-9.-]/gi, '_');
                    var name  = 'instinctor-backup-' + host + '-' + stamp + '.json';
                    var blob  = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                    var href  = URL.createObjectURL(blob);
                    var a     = document.createElement('a');
                    a.href = href; a.download = name; document.body.appendChild(a); a.click();
                    setTimeout(function(){
                        URL.revokeObjectURL(href);
                        if (a.parentNode) a.parentNode.removeChild(a);
                    }, 200);
                    $btn.prop('disabled', false).html(origHtml);
                    var pageCount = (data && typeof data.page_count !== 'undefined') ? data.page_count : '?';
                    $msg.text('Downloaded — ' + pageCount + ' pages').css('color', '#e0e0e0');
                    setTimeout(function(){ $msg.text(''); }, 4000);
                })
                .catch(function(err){
                    $btn.prop('disabled', false).html(origHtml);
                    $msg.text('Could not download. ' + (err && err.message ? err.message : 'Try again.')).css('color', '#888');
                });
        });

        

        $(document).on('click', '#settings-pwd-save', function() {
            var $btn = $('#settings-pwd-save');
            var $msg = $('#settings-pwd-msg');
            var cur  = $('#settings-pwd-current').val();
            var nw   = $('#settings-pwd-new').val();
            var cf   = $('#settings-pwd-confirm').val();

            $msg.text('').css('color', '#555');

            if (!cur || !nw || !cf) {
                $msg.text('Fill in all three fields.').css('color', '#888');
                return;
            }
            if (nw.length < 8) {
                $msg.text('New password must be at least 8 characters.').css('color', '#888');
                return;
            }
            if (nw !== cf) {
                $msg.text('New password and confirmation do not match.').css('color', '#888');
                return;
            }
            if (nw === cur) {
                $msg.text('New password must differ from the current one.').css('color', '#888');
                return;
            }

            var origHtml = $btn.html();
            $btn.prop('disabled', true).text('Saving…');

            var restBase = (window.Impulse && window.Impulse.restUrl) ? window.Impulse.restUrl : '/api/instinctor/v1/';
            var url = restBase.replace(/\/+$/, '') + '/account/password';
            var headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' };
            var nonce = (window.Impulse && window.Impulse.restNonce) ||
                        (window.wpApiSettings && window.wpApiSettings.nonce) || '';
            if (nonce) headers['X-WP-Nonce'] = nonce;

            fetch(url, {
                method: 'POST',
                credentials: 'same-origin',
                headers: headers,
                body: JSON.stringify({
                    current_password: cur,
                    new_password:     nw,
                    confirm_password: cf
                })
            })
            .then(function(r){ return r.json().then(function(j){ return { ok: r.ok, body: j }; }); })
            .then(function(res){
                $btn.prop('disabled', false).html(origHtml);
                if (res.ok && res.body && res.body.success) {
                    $('#settings-pwd-current').val('');
                    $('#settings-pwd-new').val('');
                    $('#settings-pwd-confirm').val('');
                    $msg.text('Password updated.').css('color', '#e0e0e0');
                    setTimeout(function(){ $msg.text(''); }, 4000);
                } else {
                    var err = (res.body && res.body.error) ? res.body.error : 'Could not change password.';
                    $msg.text(err).css('color', '#888');
                }
            })
            .catch(function(){
                $btn.prop('disabled', false).html(origHtml);
                $msg.text('Network error. Try again.').css('color', '#888');
            });
        });

        

        
        
        $(document).on('click', '#settings-restore-btn', function() {
            $('#settings-restore-file').trigger('click');
        });

        $(document).on('change', '#settings-restore-file', function() {
            var file = this.files && this.files[0];
            if (!file) return;
            var $input = $(this);
            var $msg   = $('#settings-restore-msg');

            
            var reader = new FileReader();
            reader.onload = function(e) {
                var data;
                try { data = JSON.parse(e.target.result); }
                catch (_err) {
                    $msg.text('Not a valid JSON file.').css('color', '#888');
                    $input.val('');
                    return;
                }
                if (!data || data.instinctor_site_export !== true || !Array.isArray(data.pages)) {
                    $msg.text('Not an Instinctor backup file.').css('color', '#888');
                    $input.val('');
                    return;
                }
                var pageCount = data.pages.length;
                var fromVer   = (data.version || '?');
                var stamp     = (data.exported_at || '').slice(0, 10) || '?';

                var existing = document.getElementById('rst-overlay');
                if (existing) existing.remove();
                var overlay = document.createElement('div');
                overlay.id = 'rst-overlay';
                overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:300;display:flex;align-items:center;justify-content:center;padding:20px';
                overlay.innerHTML =
                    '<div style="background:#1a1d21;border:1px solid #555;border-radius:6px;padding:22px;max-width:420px;width:100%">' +
                      '<div style="font-size:14px;font-weight:600;color:#fff;margin-bottom:8px">Restore this backup?</div>' +
                      '<div style="font-size:12px;color:#bbb;line-height:1.55;margin-bottom:16px">' +
                        '<div><strong style="color:#e0e0e0">' + pageCount + ' pages</strong> from backup dated <strong style="color:#e0e0e0">' + stamp + '</strong> (v' + fromVer + ').</div>' +
                        '<div style="margin-top:8px;color:#d0a36b">Pages with matching slugs will be overwritten. This action cannot be undone — download a fresh backup first if you want a rollback point.</div>' +
                      '</div>' +
                      '<div style="display:flex;gap:8px;justify-content:flex-end">' +
                        '<button id="rst-cancel" class="impulse-btn-sm">Cancel</button>' +
                        '<button id="rst-confirm" class="impulse-btn-sm" style="background:#fff;color:#1d2327;border-color:#fff">Restore</button>' +
                      '</div>' +
                    '</div>';
                document.body.appendChild(overlay);
                document.getElementById('rst-cancel').addEventListener('click', function(){
                    overlay.remove();
                    $input.val('');
                });
                document.getElementById('rst-confirm').addEventListener('click', function(){
                    overlay.remove();
                    var $btn = $('#settings-restore-btn');
                    $btn.prop('disabled', true);
                    var origHtml = $btn.html();
                    $btn.text('Restoring…');
                    $msg.text('Importing ' + pageCount + ' pages…').css('color', '#555');

                    var restBase = (window.Impulse && window.Impulse.restUrl) ? window.Impulse.restUrl : '/api/instinctor/v1/';
                    var url = restBase.replace(/\/+$/, '') + '/site/import';
                    var headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' };
                    var nonce = (window.Impulse && window.Impulse.restNonce) ||
                                (window.wpApiSettings && window.wpApiSettings.nonce) || '';
                    if (nonce) headers['X-WP-Nonce'] = nonce;

                    fetch(url, {
                        method: 'POST',
                        credentials: 'same-origin',
                        headers: headers,
                        body: JSON.stringify(data)
                    })
                        .then(function(r){
                            return r.json().then(function(j){ return [r.status, j]; });
                        })
                        .then(function(p){
                            var status = p[0], j = p[1];
                            $btn.prop('disabled', false).html(origHtml);
                            $input.val('');
                            if (status === 200 && j && j.success) {
                                $msg.text('Restored ' + j.pages + ' pages. Reload to see them.').css('color', '#e0e0e0');
                            } else if (status === 207) {
                                var errCount = (j && j.errors) ? j.errors.length : 0;
                                $msg.text('Restored ' + (j && j.pages || '?') + ' pages with ' + errCount + ' errors.').css('color', '#d0a36b');
                            } else {
                                var msg = (j && j.error) || ('HTTP ' + status);
                                $msg.text('Restore failed: ' + msg).css('color', '#888');
                            }
                        })
                        .catch(function(err){
                            $btn.prop('disabled', false).html(origHtml);
                            $input.val('');
                            $msg.text('Network error: ' + (err && err.message || 'try again')).css('color', '#888');
                        });
                });
            };
            reader.onerror = function() {
                $msg.text('Could not read file.').css('color', '#888');
                $input.val('');
            };
            reader.readAsText(file);
        });

        $(document).on('click', '#lic-upgrade-btn', function() {
            $('#lic-upgrade-btn').prop('disabled', true).text('Opening checkout…');
            $('#lic-checkout-msg').text('');

            $.post(window.Impulse.ajaxUrl, {
                action:     'instinctor_proxy_checkout',
                nonce:      window.Impulse.adminNonce,
                tier:       'pro',
                plan:       licPlan,
                billing:    licBilling,
                return_url: window.location.href
            }, function(resp) {
                $('#lic-upgrade-btn').prop('disabled', false);

                
                updateUpgradeBtnLabel();

                if (resp && resp.success && resp.data.checkout_url) {
                    window.location.href = resp.data.checkout_url;
                } else {
                    var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Checkout unavailable. Please try again.';
                    $('#lic-checkout-msg').text(msg);
                }
            }).fail(function() {
                $('#lic-upgrade-btn').prop('disabled', false);
                updateUpgradeBtnLabel();
                $('#lic-checkout-msg').text('Connection error. Please try again.');
            });
        });

        (function checkPendingLicense() {
            var qs  = new URLSearchParams(window.location.search);
            var key = qs.get('license');
            if (!key) return;

            qs.delete('license');
            var newUrl = window.location.pathname + (qs.toString() ? '?' + qs.toString() : '');
            window.history.replaceState(null, '', newUrl);

            $.post(window.Impulse.ajaxUrl, {
                action:      'instinctor_activate_license',
                nonce:       window.Impulse.adminNonce,
                license_key: key,
                source:      'checkout'
            }, function(resp) {
                if (resp && resp.success) {
                    var tier = resp.data.tier || 'pro';
                    window.Impulse.tier             = tier;
                    window.Impulse.isPro            = (tier === 'pro' || tier === 'agency');
                    window.Impulse.hasProLicense    = (tier === 'pro' || tier === 'agency');
                    window.Impulse.subscriptionActive = true;
                    renderLicStatus();
                    if (tier === 'pro' || tier === 'agency') unlockNotifRows();
                    switchStoreSection('settings');
                    $('#lic-activate-msg').text('License activated — ' + (resp.data.tier_label || 'Pro')).css('color', '#e0e0e0');
                }
            });
        })();

    })();

    $(document).on('click', '#dev-preview-toggle', function() {
        var $btn = $(this);
        $btn.prop('disabled', true);
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_toggle_preview',
            nonce: window.Impulse.adminNonce
        }, function(resp) {
            $btn.prop('disabled', false);
            if (resp && resp.success) {
                var isPreview = resp.data.status === 'preview';
                $btn.text(isPreview ? 'Stop' : 'Test');
                $('#dev-preview-msg').text(resp.data.message || '');
            }
        });
    });

    
    
    (function() {

        var LOCATION_LABELS = { head: '<head>', css: 'CSS', body_start: 'Body start', body_end: 'Body end' };

    var gSnippets = window.Impulse.globalSnippets;

    function gSnipId() {
            return 'snip_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
    }

    function saveSnippets(onDone) {

            

            
            var json = JSON.stringify(gSnippets);
            var b64;
            try { b64 = btoa(unescape(encodeURIComponent(json))); }
            catch (_e) { b64 = ''; }
            $.post(window.Impulse.ajaxUrl, {
                action:       'instinctor_save_global_snippets',
                nonce:        window.Impulse.adminNonce,
                snippets_b64: b64
            }, function(resp) {
                if (onDone) onDone(resp && resp.success);
            }).fail(function() { if (onDone) onDone(false); });
    }

    function renderList() {
            var $list = $('#gsnip-list');
            if (!gSnippets.length) {
                $list.html('<div style="font-size:11px;color:#555;padding:2px 0 6px">No snippets yet.</div>');
                return;
            }

            var html = '';
            gSnippets.forEach(function(s, i) {
                var locLabel = LOCATION_LABELS[s.location] || s.location;
                html += '<div class="gsnip-row" data-index="' + i + '" style="display:flex;align-items:center;gap:4px;padding:5px 0;border-bottom:1px solid #2a2e33">'
                    
                    + '<div class="gsnip-edit-btn" data-index="' + i + '" style="flex:1;min-width:0;cursor:pointer" title="Click to edit">'
                    +   '<div style="font-size:11px;color:#e0e0e0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + $('<div>').text(s.name).html() + '</div>'
                    +   '<div style="font-size:11px;color:#555;margin-top:1px">' + $('<div>').text(locLabel).html() + '</div>'
                    + '</div>'
                    
                    + '<label style="display:flex;align-items:center;cursor:pointer;flex-shrink:0" title="' + (s.enabled ? 'Enabled' : 'Disabled') + '">'
                    +   '<input type="checkbox" class="gsnip-toggle" data-index="' + i + '" ' + (s.enabled ? 'checked' : '') + ' style="margin:0;cursor:pointer">'
                    + '</label>'
                    
                    + '<button type="button" class="gsnip-delete-btn" data-index="' + i + '" title="Delete"'
                    +   ' style="width:24px;height:24px;padding:0;background:transparent;border:1px solid #3a3f44;border-radius:3px;color:#555;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0">'
                    +   '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>'
                    + '</button>'
                    + '</div>';
            });
            $list.html(html);
    }

    function openEditor(idx) {
            var s = idx === -1
                ? { id: gSnipId(), name: '', location: 'head', code: '', enabled: true }
                : gSnippets[idx];

            $('#gsnip-editor-id').val(idx === -1 ? s.id : String(idx));
            $('#gsnip-editor-name').val(s.name);
            $('#gsnip-editor-location').val(s.location);
            $('#gsnip-editor-code').val(s.code);
            $('#gsnip-editor-msg').text('');
            $('#gsnip-editor').show();
            $('#gsnip-add-btn').hide();
            $('#gsnip-editor-name').trigger('focus');
    }

    function closeEditor() {
            $('#gsnip-editor').hide();
            $('#gsnip-add-btn').show();
            $('#gsnip-editor-msg').text('');
    }

    $('#gsnip-add-btn').on('click', function() { openEditor(-1); });

    $('#gsnip-editor-cancel').on('click', closeEditor);

    $('#gsnip-editor-save').on('click', function() {
            var name = $('#gsnip-editor-name').val().trim();
            var code = $('#gsnip-editor-code').val();
            var location = $('#gsnip-editor-location').val();
            var rawId = $('#gsnip-editor-id').val();

            if (!name) {
                $('#gsnip-editor-msg').text('Name required.').css('color', '#999');
                return;
            }
            if (!code.trim()) {
                $('#gsnip-editor-msg').text('Code cannot be empty.').css('color', '#999');
                return;
            }

            var idx = parseInt(rawId, 10);
            if (isNaN(idx) || idx < 0) {

                

                var _existIdx = -1;
                for (var _si = 0; _si < gSnippets.length; _si++) {
                    if (gSnippets[_si] && gSnippets[_si].id === rawId) { _existIdx = _si; break; }
                }
                if (_existIdx >= 0) {
                    gSnippets[_existIdx] = $.extend({}, gSnippets[_existIdx], { name: name, location: location, code: code });
                } else {
                    gSnippets.push({ id: rawId, name: name, location: location, code: code, enabled: true });
                }
            } else {
                
                gSnippets[idx] = $.extend({}, gSnippets[idx], { name: name, location: location, code: code });
            }

            var $btn = $('#gsnip-editor-save').prop('disabled', true).text('Saving…');
            saveSnippets(function(ok) {
                $btn.prop('disabled', false).text('Save');
                if (ok) {
                    closeEditor();
                    renderList();
                } else {
                    $('#gsnip-editor-msg').text('Save failed.').css('color', '#999');
                }
            });
    });

    $(document).on('change', '.gsnip-toggle', function() {
            var idx = parseInt($(this).data('index'), 10);
            gSnippets[idx].enabled = this.checked;
            saveSnippets(null); 
    });

    $(document).on('click', '.gsnip-edit-btn', function(e) {
            if ($(e.target).is('input')) return; 
            openEditor(parseInt($(this).data('index'), 10));
    });

    $(document).on('click', '.gsnip-delete-btn', function() {
            var idx = parseInt($(this).data('index'), 10);
            var s   = gSnippets[idx];
            if (!window.impulseConfirm('Delete snippet "' + s.name + '"?')) return;
            gSnippets.splice(idx, 1);
            closeEditor();
            saveSnippets(function(ok) {
                if (ok) renderList();
            });
    });

        renderList();

    })();

    

    

    function loadProductVolumeTiers(productId) {
        var $wrap = $('#impulse-volume-tiers-wrap');
        if (!$wrap.length) return;
        $.post(ajaxurl, {
            action: 'instinctor_get_volume_tiers',
            nonce: window.Impulse.adminNonce,
            product_id: productId
        }, function(res) {
            if (!res.success) { $wrap.html('<div style="font-size:11px;color:#555">Failed to load tiers</div>'); return; }
            renderProductVolumeTiers(res.data.tiers, productId);
        });
    }
    window.loadProductVolumeTiers = loadProductVolumeTiers;

    function renderProductVolumeTiers(tiers, productId) {
        var $wrap = $('#impulse-volume-tiers-wrap');
        $wrap.data('product-id', productId); 
        if (!tiers.length) {
            $wrap.html('<div style="font-size:11px;color:#555;padding:4px 0">No tiers yet.</div>');
            return;
        }
        var currency = (window.Impulse.products && window.Impulse.products.currency) || '$';
        var html = '<table style="width:100%;border-collapse:collapse;font-size:11px">';
        html += '<tr style="color:#888"><td style="padding:3px 0">Min</td><td>Max</td><td>Type</td><td>Value</td><td></td></tr>';
        tiers.forEach(function(t) {
            var maxDisplay = t.max_quantity ? t.max_quantity : '∞';
            var typeDisplay = t.discount_type === 'percent' ? '%' : '$';
            var valDisplay  = t.discount_type === 'percent'
                ? parseFloat(t.discount_value) + '%'
                : currency + parseFloat(t.discount_value).toFixed(2);
            html += '<tr class="impulse-vol-row" data-id="' + t.id + '" style="border-top:1px solid #2a2e33">';
            html += '<td style="padding:4px 0;color:#e0e0e0">' + t.min_quantity + '</td>';
            html += '<td style="color:#e0e0e0">' + maxDisplay + '</td>';
            html += '<td style="color:#999">' + typeDisplay + '</td>';
            html += '<td style="color:#e0e0e0">' + valDisplay + ' off</td>';
            html += '<td style="text-align:right">';
            html += '<button type="button" class="impulse-vol-edit" data-id="' + t.id + '" style="background:none;border:none;cursor:pointer;color:#555;padding:2px 4px;font-size:10px">Edit</button>';
            html += '<button type="button" class="impulse-vol-delete" data-id="' + t.id + '" style="background:none;border:none;cursor:pointer;color:#555;padding:2px 4px;font-size:10px">Del</button>';
            html += '</td></tr>';
        });
        html += '</table>';
        $wrap.html(html);
        $wrap.data('tiers', tiers);
        $wrap.data('product-id', productId);
    }

    function openProductVolumeTierForm(tierId, productId) {
        var tiers = $('#impulse-volume-tiers-wrap').data('tiers') || [];
        var t = tierId ? (tiers.find(function(x){ return x.id == tierId; }) || {}) : {};
        var inp = 'height:26px;width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var html = '<div style="background:#1d2327;border:1px solid #3a3f44;border-radius:3px;padding:10px;margin-top:4px">';
        html += '<div style="display:flex;gap:6px;margin-bottom:8px">';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Min qty</div>';
        html += '<input type="number" id="pvol-min" value="' + (t.min_quantity || 2) + '" min="2" style="' + inp + '"></div>';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Max qty</div>';
        html += '<input type="number" id="pvol-max" value="' + (t.max_quantity || '') + '" placeholder="∞" style="' + inp + '"></div>';
        html += '</div>';
        html += '<div style="display:flex;gap:6px;margin-bottom:10px">';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Type</div>';
        html += '<div style="display:flex;gap:0">';
        html += '<button type="button" class="impulse-btn-sm pvol-type-btn' + (t.discount_type==='flat'?'':' active') + '" data-type="percent" style="flex:1;border-radius:3px 0 0 3px;font-size:11px">%</button>';
        html += '<button type="button" class="impulse-btn-sm pvol-type-btn' + (t.discount_type==='flat'?' active':'') + '" data-type="flat" style="flex:1;border-radius:0 3px 3px 0;font-size:11px">$</button>';
        html += '</div>';
        html += '<input type="hidden" id="pvol-type" value="' + (t.discount_type || 'percent') + '"></div>';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Value</div>';
        html += '<input type="number" id="pvol-value" value="' + parseFloat(t.discount_value || 10) + '" min="0.01" step="0.01" style="' + inp + '"></div>';
        html += '</div>';
        html += '<input type="hidden" id="pvol-id" value="' + (t.id || 0) + '">';
        html += '<input type="hidden" id="pvol-product-id" value="' + productId + '">';
        html += '<div style="display:flex;gap:6px">';
        html += '<button type="button" id="pvol-save" class="impulse-btn-sm" style="flex:1">Save</button>';
        html += '<button type="button" id="pvol-cancel" class="impulse-btn-sm">Cancel</button>';
        html += '</div></div>';
        
        $('#impulse-volume-tiers-wrap').after(html.replace('<div style', '<div id="impulse-vol-form" style'));
        $('#impulse-add-volume-tier').hide();
    }

    $(document).on('click', '.impulse-bundle-type-btn', function() {
        var btype = $(this).data('btype');
        $('.impulse-bundle-type-btn').removeClass('active');
        $(this).addClass('active');
        $('[name="bundle_type"]').val(btype);
        $('#impulse-bundle-picks-row').toggle(btype === 'build_your_own');
    });

    $(document).on('click', '.impulse-bundle-disc-btn', function() {
        $('.impulse-bundle-disc-btn').removeClass('active');
        $(this).addClass('active');
        $('[name="bundle_discount_type"]').val($(this).data('dtype'));
    });

    $(document).on('click', '.impulse-bundle-remove-product', function() {
        $(this).closest('.impulse-bundle-chip').remove();
        _updateBundleProductsJson();
    });

    $(document).on('click', '#impulse-bundle-add-product', function() {
        openBundleProductModal();
    });

    function _updateBundleProductsJson() {
        var ids = [];
        $('#impulse-bundle-products-list .impulse-bundle-chip').each(function() {
            ids.push(parseInt($(this).data('id')));
        });
        $('[name="bundle_products_json"]').val(JSON.stringify(ids));
    }

    $(document).on('click', '#pb-pick-bundle-btn', function() {
        var $btn = $(this);
        
        if ($('.pb-bundle-dropdown').length) { $('.pb-bundle-dropdown').remove(); return; }
        $btn.text('Loading…');
        $.post(ajaxurl, { action: 'instinctor_get_bundles', nonce: window.Impulse.adminNonce }, function(res) {
            var bundles = (res && res.data && res.data.bundles) || [];
            if (!bundles.length) {
                $btn.text('No bundles found');
                setTimeout(function() { $btn.text('Select a bundle…'); }, 2000);
                return;
            }
            $btn.text('Select a bundle…');
            var dd = '<div class="pb-bundle-dropdown" style="position:absolute;left:0;right:0;top:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;max-height:180px;overflow-y:auto;z-index:99;margin-top:2px">';
            bundles.forEach(function(b) {
                var count = (b.products || []).length;
                dd += '<div class="pb-bundle-option" data-id="' + b.id + '" data-name="' + escapeHtml(b.name) + '" style="padding:6px 8px;font-size:11px;color:#e0e0e0;cursor:pointer;display:flex;justify-content:space-between;border-bottom:1px solid #1a1d21">';
                dd += '<span>' + escapeHtml(b.name) + '</span>';
                dd += '<span style="color:#666">' + count + ' item' + (count !== 1 ? 's' : '') + '</span>';
                dd += '</div>';
            });
            dd += '</div>';
            $btn.closest('div').css('position', 'relative').append(dd);
        }).fail(function() {
            $btn.text('Failed to load');
            setTimeout(function() { $btn.text('Select a bundle…'); }, 2000);
        });
    });

    $(document).on('click', '.pb-bundle-option', function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        $('input[name="bundle_id"]').val(id);
        $('input[name="bundle_label"]').val(name);
        $('#pb-pick-bundle-btn').text(name).css('color', '#e0e0e0');
        $('.pb-bundle-dropdown').remove();
        
        var elId = $('.impulse-panel-right').data('element-id');
        if (elId) {
            clearTimeout(autoSaveTimer);
            clearTimeout(autoRefreshTimer);
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            existingSettings.bundle_id = id;
            existingSettings.bundle_label = name;
            $('.impulse-panel-right').data('existing-settings', existingSettings);
            enqueueSave(elId, existingSettings, function(success) {
                if (success) {
                    
                    isRefreshing = false;
                    pendingRefresh = false;
                    refreshPreview();
                }
                setTimeout(function() { openSettings(elId, 'product_bundle'); }, 600);
            });
        }
    });

    $(document).on('mousedown', function(e) {
        if (!$(e.target).closest('.pb-bundle-dropdown, #pb-pick-bundle-btn').length) {
            $('.pb-bundle-dropdown').remove();
        }
    });

    $(document).on('click', '#pb-clear-bundle-btn', function() {
        var elId = $('.impulse-panel-right').data('element-id');
        if (elId) {
            clearTimeout(autoSaveTimer);
            clearTimeout(autoRefreshTimer);
            var existingSettings = $('.impulse-panel-right').data('existing-settings') || {};
            existingSettings.bundle_id = 0;
            existingSettings.bundle_label = '';
            $('.impulse-panel-right').data('existing-settings', existingSettings);
            enqueueSave(elId, existingSettings, function(success) {
                if (success) {
                    isRefreshing = false;
                    pendingRefresh = false;
                    refreshPreview();
                }
                setTimeout(function() { openSettings(elId, 'product_bundle'); }, 600);
            });
        }
    });

    $(document).on('click', '#impulse-add-volume-tier', function() {
        var productId = $('.impulse-product-edit-form').data('id');
        if (!productId) { showToast('Save the product first, then add volume tiers.', 'error'); return; }
        $('#impulse-volume-tiers-wrap').data('product-id', productId);
        openProductVolumeTierForm(null, productId);
    });

    $(document).on('click', '.pvol-type-btn', function() {
        $(this).addClass('active').siblings('.pvol-type-btn').removeClass('active');
        $('#pvol-type').val($(this).data('type'));
    });

    $(document).on('click', '.impulse-vol-edit', function() {
        var id = parseInt($(this).data('id'));
        var productId = $('#impulse-volume-tiers-wrap').data('product-id');
        $('#impulse-vol-form').remove();
        openProductVolumeTierForm(id, productId);
    });

    $(document).on('click', '.impulse-vol-delete', function() {
        var id = parseInt($(this).data('id'));
        if (!window.impulseConfirm('Delete this tier?')) return;
        var productId = $('#impulse-volume-tiers-wrap').data('product-id');
        $.post(ajaxurl, { action: 'instinctor_delete_volume_tier', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (res.success) loadProductVolumeTiers(productId);
            else showToast(res.data || 'Error', 'error');
        });
    });

    $(document).on('click', '#pvol-cancel', function() {
        $('#impulse-vol-form').remove();
        $('#impulse-add-volume-tier').show();
    });

    $(document).on('click', '#pvol-save', function() {
        var min = parseInt($('#pvol-min').val());
        var val = parseFloat($('#pvol-value').val());
        if (min < 2) { showToast('Min quantity must be 2+', 'error'); return; }
        if (val <= 0) { showToast('Discount must be > 0', 'error'); return; }
        var data = {
            action: 'instinctor_save_volume_tier',
            nonce: window.Impulse.adminNonce,
            id: $('#pvol-id').val(),
            product_id: $('#pvol-product-id').val(),
            min_quantity: min,
            max_quantity: $('#pvol-max').val() || '',
            discount_type: $('#pvol-type').val(),
            discount_value: val
        };
        $.post(ajaxurl, data, function(res) {
            if (res.success) {
                $('#impulse-vol-form').remove();
                $('#impulse-add-volume-tier').show();
                loadProductVolumeTiers(data.product_id);
            } else {
                showToast(res.data || 'Error', 'error');
            }
        });
    });

    function loadVolumeTiers() {
        $.post(ajaxurl, { action: 'instinctor_get_volume_tiers', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) return;
            renderVolumeTierList(res.data.tiers);
        });
    }

    function renderVolumeTierList(tiers) {
        var html = '';
        if (!tiers.length) {
            html = '<div style="color:#555;font-size:11px;text-align:center;padding:24px 0">No tiers yet. Click + Add Tier to create one.</div>';
        } else {
            tiers.forEach(function(t) {
                var scope = t.product_id ? 'Product #' + t.product_id : (t.category_id ? 'Category #' + t.category_id : 'Global');
                var disc = t.discount_type === 'percent' ? t.discount_value + '% off' : '$' + parseFloat(t.discount_value).toFixed(2) + ' off';
                var qty = 'Buy ' + t.min_quantity + (t.max_quantity ? '–' + t.max_quantity : '+');
                html += '<div class="impulse-volume-row" style="display:flex;align-items:center;justify-content:space-between;padding:7px 0;border-bottom:1px solid #2a2e33">';
                html += '<div style="flex:1;min-width:0">';
                html += '<div style="font-size:11px;color:#e0e0e0">' + qty + ' → ' + disc + '</div>';
                html += '<div style="font-size:11px;color:#666;margin-top:2px">' + scope + '</div>';
                html += '</div>';
                html += '<div style="display:flex;gap:6px;flex-shrink:0;margin-left:8px">';
                html += '<button class="impulse-volume-edit impulse-btn-sm" data-id="' + t.id + '">Edit</button>';
                html += '<button class="impulse-volume-delete impulse-btn-sm" data-id="' + t.id + '" style=\"color:#555\">Del</button>';
                html += '</div>';
                html += '</div>';
            });
        }
        var _volTarget = targetId ? '#' + targetId : '#volume-list-wrap';
        $(_volTarget).html(html);
        window._volumeData = tiers;
    }

    function openVolumeTierForm(tier, targetId) {
        var t = tier || { id: 0, product_id: '', category_id: '', min_quantity: 2, max_quantity: '', discount_type: 'percent', discount_value: 10 };
        var inp = 'height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var sel = 'height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 6px;box-sizing:border-box';
        var html = '<div>';
        html += '<div style="display:flex;gap:6px;margin-bottom:8px">';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Min qty</div><input type="number" id="vol-min" value="' + (t.min_quantity||2) + '" min="2" style="width:100%;' + inp + '"></div>';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Max qty</div><input type="number" id="vol-max" value="' + (t.max_quantity||'') + '" min="0" placeholder="No limit" style="width:100%;' + inp + '"></div>';
        html += '</div>';
        html += '<div style="display:flex;gap:6px;margin-bottom:8px">';
        html += '<div style="flex:0 0 100px"><div style="font-size:11px;color:#999;margin-bottom:3px">Discount</div><select id="vol-disc-type" style="width:100%;' + sel + '"><option value="percent"' + (t.discount_type==='percent'?' selected':'') + '>Percent</option><option value="flat"' + (t.discount_type==='flat'?' selected':'') + '>Flat $</option></select></div>';
        html += '<div style="flex:1"><div style="font-size:11px;color:#999;margin-bottom:3px">Value</div><input type="number" id="vol-disc-value" value="' + parseFloat(t.discount_value||0) + '" min="0.01" step="0.01" style="width:100%;' + inp + '"></div>';
        html += '</div>';
        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#999;margin-bottom:3px">Scope (optional — blank for global)</div>';
        html += '<div style="display:flex;gap:6px">';
        html += '<input type="number" id="vol-product-id" value="' + (t.product_id||'') + '" placeholder="Product ID" style="flex:1;' + inp + '">';
        html += '<input type="number" id="vol-category-id" value="' + (t.category_id||'') + '" placeholder="Category ID" style="flex:1;' + inp + '">';
        html += '</div></div>';
        html += '<input type="hidden" id="vol-id" value="' + (t.id||0) + '">';
        html += '<div style="display:flex;gap:6px"><button id="vol-save-btn" class="impulse-btn-sm impulse-btn-primary">Save Tier</button>';
        if (t.id) html += '<button id="vol-cancel-btn" class="impulse-btn-sm">Cancel</button>';
        html += '</div></div>';
        $('#volume-list-wrap').html(html);
    }

    $(document).on('click', '#volume-add-btn', function() { volumeLoaded = true; openCrudRightPanel('volume_discounts', null); });
    $(document).on('click', '.impulse-volume-edit', function(e) {
        e.stopPropagation();
        var id = parseInt($(this).data('id'));
        var t = (window._volumeData||[]).find(function(x){ return x.id==id; });
        if (t) openVolumeTierForm(t);
    });
    $(document).on('click', '.impulse-volume-delete', function(e) {
        e.stopPropagation();
        var id = parseInt($(this).data('id'));
        if (!window.impulseConfirm('Delete this tier?')) return;
        $.post(ajaxurl, { action: 'instinctor_delete_volume_tier', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (res.success) { volumeLoaded = false; loadVolumeTiers(); }
            else showImpulseToast(res.data || 'Error', 'error');
        });
    });
    $(document).on('click', '#vol-cancel-btn', function() { loadVolumeTiers(); });
    $(document).on('click', '#vol-save-btn', function() {
        var data = {
            action: 'instinctor_save_volume_tier', nonce: window.Impulse.adminNonce,
            id: $('#vol-id').val(), min_quantity: $('#vol-min').val(), max_quantity: $('#vol-max').val(),
            discount_type: $('#vol-disc-type').val(), discount_value: $('#vol-disc-value').val(),
            product_id: $('#vol-product-id').val(), category_id: $('#vol-category-id').val()
        };
        if (parseInt(data.min_quantity) < 2) { showImpulseToast('Min quantity must be 2+', 'error'); return; }
        if (parseFloat(data.discount_value) <= 0) { showImpulseToast('Discount must be > 0', 'error'); return; }
        $.post(ajaxurl, data, function(res) {
            if (res.success) { showImpulseToast('Tier saved'); volumeLoaded = false; loadVolumeTiers(); }
            else showImpulseToast(res.data || 'Error', 'error');
        });
    });

    

    var featureStatusConfig = {
        'bundles':           { name: 'Bundles',           loadStats: null,                     loadTileStats: null,                       loadCardStats: null },
        'product_addons':    { name: 'Add-Ons',           loadStats: null,                     loadTileStats: null,                       loadCardStats: null },
        'coupons':           { name: 'Coupons',           loadStats: null,                     loadTileStats: null,                       loadCardStats: null },
        'loyalty':           { name: 'Loyalty',           loadStats: null,                     loadTileStats: null,                       loadCardStats: null },
        'gift_cards':        { name: 'Gift Cards',        loadStats: null,                     loadTileStats: null,                       loadCardStats: null }};

    function showFeatureStatusPanel(key) {
        var cfg = featureStatusConfig[key];
        if (!cfg) { $('#feature-status-panel').hide(); $('#settings-right-header').hide(); return; }
        if (typeof window.storeRightExpand === 'function') window.storeRightExpand();
        $('#settings-right-header').show().find('span').text(cfg.name);
        $('#feature-status-panel').attr('data-feature', key).show();
        $('#feature-status-name').hide(); 
        $('#feature-stats-grid').html('');
        $('#feature-autosave-indicator').css('opacity', 0);
        $('#feature-status-toggle').prop('checked', false);
        $('#feature-status-label').text('Inactive');
        
        $('#settings-email-panel').hide();
        $('#settings-detail-content').hide();
        if (cfg.loadStats) cfg.loadStats();
    }

    function cardStat(value, label) {
        return '<span class="impulse-feature-card-stat">'
            + '<span class="impulse-feature-card-stat-val">' + value + '</span>'
            + '<span class="impulse-feature-card-stat-label">' + label + '</span>'
            + '</span>';
    }

    

    function crudCardList(items, renderRow) {
        if (!items.length) return '<div style="font-size:11px;color:#555;text-align:center;padding:12px 0">None yet.</div>';
        var html = '';
        items.forEach(function(item) { html += renderRow(item); });
        return html;
    }

    function crudCardRow(feature, id, col1, col2) {
        return '<div class=\"impulse-card-list-row\" data-feature=\"' + feature + '\" data-id=\"' + id + '\" style=\"display:flex;justify-content:space-between;align-items:center;padding:5px 0;border-bottom:1px solid #1a1d21;cursor:pointer\">'
            + '<span style=\"font-size:11px;color:#e0e0e0;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap\">' + col1 + '</span>'
            + '<span style=\"font-size:11px;color:#555;margin:0 6px;flex-shrink:0\">' + col2 + '</span>'
            + '<svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#3a3f44\" stroke-width=\"2\" style=\"flex-shrink:0\"><polyline points=\"9 18 15 12 9 6\"/></svg>'
            + '</div>';
    }

    
    
    function openBundleForm(bundle, targetId) {
        var $target = $('#' + (targetId || 'settings-detail-content'));
        var b = bundle || { id: 0, name: '', bundle_type: 'fixed', discount_type: 'percent', discount_value: 10, min_products: 0, max_products: 0, is_active: 1, products: [] };
        var existingProducts = Array.isArray(b.products) ? b.products : (function(){ try { return JSON.parse(b.products || '[]'); } catch(e) { return []; } })();
        var existingProductNames = b.product_names || {};
        var isByo = b.bundle_type === 'build_your_own';
        var inpStyle = 'height:26px;width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var row = function(labelText, ctrl) {
            return '<div style="display:flex;align-items:center;margin-bottom:8px">'
                + '<div style="flex:1;font-size:11px;color:#999;white-space:nowrap">' + labelText + '</div>'
                + '<div style="flex:1;min-width:0">' + ctrl + '</div>'
                + '</div>';
        };
        var html = '<div style="padding:8px 12px 16px">';
        var isActive = parseInt(b.is_active || 1);
        html += '<div style="display:flex;margin-bottom:8px">';
        html += '<button type="button" class="impulse-btn-sm bundle-status-btn' + (isActive ? ' active' : '') + '" data-status="active" style="border-radius:3px 0 0 3px;flex:1">Active</button>';
        html += '<button type="button" class="impulse-btn-sm bundle-status-btn' + (!isActive ? ' active' : '') + '" data-status="inactive" style="border-radius:0 3px 3px 0;flex:1">Inactive</button>';
        html += '</div>';
        html += '<div style="margin-bottom:8px">';
        html += '<div class="impulse-btn-group" style="display:flex;width:100%">';
        html += '<button type="button" class="impulse-btn-sm bundle-type-btn' + (b.bundle_type === 'fixed' ? ' active' : '') + '" data-type="fixed" style="flex:1">Fixed</button>';
        html += '<button type="button" class="impulse-btn-sm bundle-type-btn' + (b.bundle_type === 'build_your_own' ? ' active' : '') + '" data-type="build_your_own" style="flex:1">Build your own</button>';
        html += '</div>';
        html += '<input type="hidden" id="bundle-type" value="' + b.bundle_type + '">';
        html += '</div>';
        html += row('Name', '<input type="text" id="bundle-name" value="' + $('<s>').text(b.name).html() + '" style="' + inpStyle + '">');
        html += row('Discount',
            '<div style="display:flex;width:100%">'
            + '<div class="impulse-btn-group" style="flex-shrink:0">'
            + '<button type="button" class="impulse-btn-sm bundle-disc-type-btn' + (b.discount_type === 'percent' ? ' active' : '') + '" data-dtype="percent" style="width:30px;padding:0">%</button>'
            + '<button type="button" class="impulse-btn-sm bundle-disc-type-btn' + (b.discount_type === 'flat' ? ' active' : '') + '" data-dtype="flat" style="width:30px;padding:0">$</button>'
            + '</div>'
            + '<input type="text" inputmode="decimal" id="bundle-discount-value" value="' + parseFloat(b.discount_value || 0) + '" style="flex:1;min-width:0;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-left:none;border-radius:0 3px 3px 0;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box">'
            + '</div>'
            + '<input type="hidden" id="bundle-discount-type" value="' + b.discount_type + '">'
        );
        html += '<div id="bundle-picks-row"' + (isByo ? '' : ' style="display:none"') + '>';
        html += row('Picks',
            '<div style="display:flex;align-items:center;gap:4px;width:100%">'
            + '<input type="text" inputmode="numeric" id="bundle-min" value="' + (b.min_products || 0) + '" style="flex:1;min-width:0;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;text-align:center;box-sizing:border-box">'
            + '<span style="font-size:11px;color:#888;flex-shrink:0">to</span>'
            + '<input type="text" inputmode="numeric" id="bundle-max" value="' + (b.max_products || 0) + '" style="flex:1;min-width:0;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;text-align:center;box-sizing:border-box">'
            + '</div>'
        );
        html += '<div style="font-size:10px;color:#888;text-align:right;margin-top:-3px;margin-bottom:6px">how many items the customer picks · 0 = no limit</div>';
        html += '</div>';
        html += '<div id="bundle-products-list" style="margin-bottom:6px">';
        if (existingProducts.length) {
            existingProducts.forEach(function(pid) {
                var pname = existingProductNames[pid] || ('Product #' + pid);
                var pimg  = (b.product_images || {})[pid] || '';
                html += '<div class="bundle-product-chip" data-id="' + pid + '" style="display:flex;align-items:center;gap:6px;height:30px;padding:0 0 0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;margin-bottom:3px;font-size:11px;color:#e0e0e0">';
                if (pimg) html += '<img src="' + pimg + '" style="width:20px;height:20px;object-fit:cover;border-radius:2px;flex-shrink:0">';
                html += '<span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + $('<s>').text(pname).html() + '</span>';
                html += '<button type="button" class="bundle-remove-product" data-id="' + pid + '" style="width:26px;height:26px;flex-shrink:0;background:none;border:none;border-left:1px solid #3a3f44;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="#999" 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 += '<div id="bundle-no-products" style="font-size:11px;color:#888;padding:2px 0">No products yet.</div>';
        }
        html += '</div>';
        html += '<button type="button" id="bundle-add-product-btn" class="impulse-btn-sm" style="width:100%;margin-bottom:8px">+ Add a Product</button>';
        html += '<input type="hidden" id="bundle-products-json" value="' + $('<s>').text(JSON.stringify(existingProducts)).html() + '">';
        html += '<input type="hidden" id="bundle-id" value="' + (b.id || 0) + '">';
        if (b.id) {
            html += '<div style="margin-top:8px"><button type="button" class="impulse-btn-sm btn-delete-bundle" data-id="' + b.id + '">Delete bundle</button></div>';
        }
        html += '</div>';
        $target.html(html);
        $target.off('input.bundle click.bundle')
            .on('input.bundle', '#bundle-name,#bundle-discount-value,#bundle-min,#bundle-max', scheduleBundleSave)
            .on('click.bundle', '.bundle-type-btn', function() {
                var t = $(this).data('type');
                $('.bundle-type-btn').removeClass('active'); $(this).addClass('active');
                $('#bundle-type').val(t);
                $('#bundle-picks-row').toggle(t === 'build_your_own');
                scheduleBundleSave();
            })
            .on('click.bundle', '.bundle-disc-type-btn', function() {
                $('.bundle-disc-type-btn').removeClass('active'); $(this).addClass('active');
                $('#bundle-discount-type').val($(this).data('dtype'));
                scheduleBundleSave();
            })
            .on('click.bundle', '.bundle-status-btn', function() {
                $('.bundle-status-btn').removeClass('active'); $(this).addClass('active');
                scheduleBundleSave();
            });
    }

    var _bundleSaveTimer = null;
    window._bundleSaveTimer = _bundleSaveTimer;
    function scheduleBundleSave() {
        clearTimeout(window._bundleSaveTimer);
        window._bundleSaveTimer = setTimeout(saveBundleNow, 800);
    }

    var _bundleSaveInFlight = false;
    var _bundleSavePending  = false;
    function saveBundleNow() {
        if (_bundleSaveInFlight) { _bundleSavePending = true; return; }
        var products = [];
        try { products = JSON.parse($('#bundle-products-json').val() || '[]'); } catch(e) {}
        var data = {
            action: 'instinctor_save_bundle', nonce: window.Impulse.adminNonce,
            id: $('#bundle-id').val(),
            name: $('#bundle-name').val(),
            bundle_type: $('#bundle-type').val(),
            discount_type: $('#bundle-discount-type').val(),
            discount_value: $('#bundle-discount-value').val(),
            is_active: $('.bundle-status-btn.active').data('status') === 'active' ? 1 : 0,
            min_products: $('#bundle-min').val(),
            max_products: $('#bundle-max').val(),
            products: products
        };
        if (!data.name) return;
        _bundleSaveInFlight = true;
        $.post(ajaxurl, data, function(res) {
            _bundleSaveInFlight = false;
            if (res.success) {
                if (res.data && res.data.id) $('#bundle-id').val(res.data.id);
                if (productsTabMode === 'bundles') loadBundlesCenter();
            } else showImpulseToast(res.data || 'Error', 'error');
            if (_bundleSavePending) { _bundleSavePending = false; saveBundleNow(); }
        });
    }

    function getBundleProductIds() {
        try { return JSON.parse($('#bundle-products-json').val() || '[]'); } catch(e) { return []; }
    }

    function openBundleProductModal() {
        $('.impulse-bundle-product-modal').remove();
        var modal = '<div class="impulse-bundle-product-modal" style="position:fixed;inset:0;background:rgba(0,0,0,0);z-index:1000020;display:flex;align-items:center;justify-content:center;transition:background 0.15s ease-in-out">';
        modal += '<div class="impulse-bundle-product-modal-content" style="background:#1a1d21;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">';
        modal += '<div style="padding:12px 16px;border-bottom:1px solid #3a3f44;display:flex;justify-content:space-between;align-items:center">';
        modal += '<div style="font-weight:500;font-size:14px;color:#fff">Add Products to Bundle</div>';
        modal += '<button type="button" class="impulse-close-bundle-modal" style="background:none;border:none;font-size:18px;cursor:pointer;color:#666">&times;</button>';
        modal += '</div>';
        modal += '<div style="padding:12px 16px;border-bottom:1px solid #3a3f44">';
        modal += '<input type="text" id="bundle-product-search" placeholder="Search products..." style="width:100%;height:26px;padding:0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;box-sizing:border-box">';
        modal += '</div>';
        modal += '<div id="bundle-product-list" style="flex:1;overflow-y:auto;padding:12px;display:grid;grid-template-columns:repeat(4,1fr);gap:8px">';
        modal += '<div style="grid-column:1/-1;text-align:center;padding:30px;color:#666">Loading products...</div>';
        modal += '</div></div></div>';
        $('body').append(modal);
        setTimeout(function() {
            $('.impulse-bundle-product-modal').css('background','rgba(0,0,0,0.6)');
            $('.impulse-bundle-product-modal-content').css({opacity:1,transform:'translateY(0)'});
        }, 10);
        loadBundleProductList('');
    }

    function loadBundleProductList(search) {
        var existing = getBundleProductIds();
        $.get(window.Impulse.api + 'products', { search: search || '', per_page: 50, _wpnonce: window.Impulse.nonce }, function(response) {
            var products = response.data || response || [];
            if (!Array.isArray(products)) products = [];
            var html = '';
            products.forEach(function(p) {
                var alreadyAdded = existing.indexOf(p.id) !== -1;
                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="bundle-product-pick-item' + (alreadyAdded ? ' added' : '') + '" data-id="' + p.id + '" data-name="' + (p.name||'').replace(/"/g,'&quot;') + '" style="border:1px solid ' + (alreadyAdded?'#fff':'#3a3f44') + ';border-radius:3px;overflow:hidden;cursor:pointer;background:#2a2e33;transition:border-color 0.15s">';
                html += '<div style="aspect-ratio:1;background:#1a1d21;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\'">';
                else html += '<span style="color:#666;font-size:10px">No image</span>';
                html += '</div><div style="padding:6px;font-size:10px;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#e0e0e0">' + (p.name||'Untitled') + '</div>';
                if (alreadyAdded) html += '<div style="text-align:center;padding:0 6px 4px;font-size:9px;color:#e0e0e0">✓ Added</div>';
                html += '</div>';
            });
            $('#bundle-product-list').html(html || '<div style="grid-column:1/-1;text-align:center;padding:30px;color:#666">No products found</div>');
        }).fail(function() {
            $('#bundle-product-list').html('<div style="grid-column:1/-1;text-align:center;padding:30px;color:#666">Failed to load products</div>');
        });
    }

    var _bundleProductSearchTimer;
    $(document).on('input', '#bundle-product-search', function() {
        clearTimeout(_bundleProductSearchTimer);
        var q = $(this).val();
        _bundleProductSearchTimer = setTimeout(function(){ loadBundleProductList(q); }, 300);
    });

    $(document).on('click', '#bundle-add-product-btn', function() { openBundleProductModal(); });

    $(document).on('click', '.bundle-product-pick-item', function() {
        var id = parseInt($(this).data('id'));
        var name = $(this).data('name');
        var ids = getBundleProductIds();
        if (ids.indexOf(id) !== -1) return;
        ids.push(id);
        $('#bundle-products-json').val(JSON.stringify(ids));
        $('#bundle-no-products').remove();
        var chip = '<div class="bundle-product-chip" data-id="' + id + '" style="display:flex;align-items:center;gap:6px;height:30px;padding:0 0 0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;margin-bottom:3px;font-size:11px;color:#e0e0e0">';
        chip += '<span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + $('<s>').text(name).html() + '</span>';
        chip += '<button type="button" class="bundle-remove-product" data-id="' + id + '" style="width:26px;height:26px;flex-shrink:0;background:none;border:none;border-left:1px solid #3a3f44;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="#999" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>';
        chip += '</div>';
        $('#bundle-products-list').append(chip);
        $(this).css('border-color','#fff').addClass('added').append('<div style="text-align:center;padding:0 6px 4px;font-size:9px;color:#e0e0e0">✓ Added</div>');
        scheduleBundleSave();
    });

    $(document).on('mouseenter', '.bundle-product-pick-item:not(.added)', function(){ $(this).css('border-color','#fff'); });
    $(document).on('mouseleave', '.bundle-product-pick-item:not(.added)', function(){ $(this).css('border-color','#3a3f44'); });
    $(document).on('click', '.impulse-close-bundle-modal', function(){ $('.impulse-bundle-product-modal').remove(); });
    $(document).on('click', '.impulse-bundle-product-modal', function(e){ if (e.target===this) $(this).remove(); });

    $(document).on('click', '.bundle-remove-product', function() {
        var id = parseInt($(this).data('id'));
        $(this).closest('.bundle-product-chip').remove();
        var ids = getBundleProductIds().filter(function(x){ return x !== id; });
        $('#bundle-products-json').val(JSON.stringify(ids));
        if (!ids.length) {
            if (!$('#bundle-no-products').length) {
                $('#bundle-products-list').prepend('<div id="bundle-no-products" style="font-size:11px;color:#555;padding:6px 0">No products added yet.</div>');
            }
        }
        scheduleBundleSave();
    });

    function deleteBundleById(id, clearRight) {
        $.post(ajaxurl, { action: 'instinctor_delete_bundle', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (res.success) {
                if (clearRight) crudRightPanelEmpty();
                if (productsTabMode === 'bundles') loadBundlesCenter();
                
                var $cardWrap = $('.impulse-feature-card[data-feature="bundles"] .impulse-card-list-inner');
                if ($cardWrap.length) loadBundlesCard($cardWrap.attr('id') || 'bundles-card-list');
                showImpulseToast('Bundle deleted');
            } else showImpulseToast(res.data || 'Error', 'error');
        });
    }
    $(document).on('click', '.btn-delete-bundle', function(e) {
        e.stopPropagation();
        deleteBundleById(parseInt($(this).data('id')), true);
    });
    $(document).on('click', '.btn-delete-bundle-list', function(e) {
        e.stopPropagation();
        var id = parseInt($(this).data('id'));
        var openId = parseInt($('#bundle-id').val() || 0);
        deleteBundleById(id, id === openId);
    });

        function loadBundlesCard(containerId) {
        var $c = $('#' + containerId);
        $.post(ajaxurl, { action: 'instinctor_get_bundles', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) { $c.html('<div style="color:#555;font-size:11px;padding:8px">Failed to load bundles</div>'); return; }
            var bundles = res.data.bundles;
            window._bundleData = bundles;
            var html = '';
            if (!bundles.length) {
                html = '<div style="font-size:11px;color:#555;text-align:center;padding:12px 0">None yet.</div>';
            } else {
                bundles.forEach(function(b) {
                    var disc = b.discount_type === 'percent' ? b.discount_value + '% off' : '$' + parseFloat(b.discount_value).toFixed(2) + ' off';
                    var products = Array.isArray(b.products) ? b.products : (function(){ try { return JSON.parse(b.products||'[]'); } catch(e){ return []; } })();
                    var names = (b.product_names && typeof b.product_names === 'object') ? Object.values(b.product_names) : [];
                    var sub = names.length ? names.slice(0,3).join(', ') + (names.length > 3 ? '…' : '') : (products.length + ' product' + (products.length !== 1 ? 's' : ''));
                    html += '<div class="impulse-card-list-row" data-feature="bundles" data-id="' + b.id + '" style="display:flex;align-items:center;padding:6px 0;border-bottom:1px solid #1a1d21;gap:6px">';
                    html += '<div style="flex:1;min-width:0;overflow:hidden;cursor:pointer">';
                    html += '<div style="font-size:11px;color:#e0e0e0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(b.name) + '</div>';
                    html += '<div style="font-size:10px;color:#555;margin-top:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(sub) + '</div>';
                    html += '</div>';
                    html += '<span style="font-size:11px;color:#555;flex-shrink:0">' + escapeHtml(disc) + '</span>';
                    html += '<button type="button" class="impulse-btn-sm btn-delete-bundle-list" data-id="' + b.id + '" style="width:26px;padding:0;flex-shrink:0" title="Delete">&times;</button>';
                    html += '</div>';
                });
            }
            $c.html(html);
            $('#card-stats-bundles').html(cardStat(bundles.length, 'Bundles'));
        }).fail(function(xhr) {
            $c.html('<div style="color:#555;font-size:11px;padding:8px">Error: ' + (xhr.status || 'unknown') + ' — check PHP error log</div>');
        });
    }

    function openAddonForm(addon, targetId) {}

    var _activeCrudFeature = null;
    window._activeCrudFeature = _activeCrudFeature;

    function openCrudRightPanel(feature, item) {
        _activeCrudFeature = feature;
        window._activeCrudFeature = feature;
        var labels = { bundles: 'Bundle', product_addons: 'Add-On', coupons: 'Coupon', gift_cards: 'Gift Card' };
        var title = (item ? 'Edit ' : 'New ') + (labels[feature] || feature);

        $('[data-workspace="store"] .impulse-store-right-content').hide();
        $('[data-workspace="store"] .impulse-store-right-content[data-section="products"]').show();
        setProductsRightTitle(title);
        if (feature === 'bundles')        { openBundleForm(item, 'impulse-products-edit'); return; }
        if (feature === 'product_addons') { openAddonForm(item, 'impulse-products-edit'); return; }
        if (feature === 'coupons')        { openCouponForm(item, 'impulse-products-edit'); return; }
        if (feature === 'gift_cards')     { openGiftCardForm(item, 'impulse-products-edit'); return; }
    }

    function setProductsRightTitle(text) {
        $('#products-right-title').text(text);
        $('#products-right-header').toggle(!!text);
    }
    window.setProductsRightTitle = setProductsRightTitle;

    function crudRightPanelEmpty() {
        setProductsRightTitle('');
        $('#impulse-products-edit').html('');
        storeRightCollapse();
    }
    window.crudRightPanelEmpty = crudRightPanelEmpty;

    $(document).on('click', '.impulse-card-add-btn', function(e) {
        e.stopPropagation();
        var feature = $(this).data('feature');
        var $card = $(this).closest('.impulse-feature-card');
        if (!$card.hasClass('expanded')) expandFeatureCard(feature, $card.data('section'));
        openCrudRightPanel(feature, null);
    });

    $(document).on('click', '.impulse-card-list-row[data-feature]', function() {
        var feature = $(this).data('feature');
        var id = $(this).data('id');
        var item = null;
        if (feature === 'bundles')          item = (window._bundleData   || []).find(function(x){ return x.id == id; });
        if (feature === 'product_addons')   item = (window._addonData    || []).find(function(x){ return x.id == id; });
        if (feature === 'coupons')          item = (window._couponData   || []).find(function(x){ return x.id == id; });
        if (feature === 'gift_cards')       item = (window._giftCardData || []).find(function(x){ return x.id == id; });
        if (item) openCrudRightPanel(feature, item);
    });

    

    var bookingsState = {
        bookings:    [],
        services:    [],
        filters:     { status: 'upcoming', search: '', date: '' },
        selected:    null,
        initialized: false,
        loading:     false,
        bookingDates: new Set(),
        calScrollTop: null,
        calObserver:  null,
        activeForm:   null   
    };

    function setBookingsRightTitle(text) {
        var hasTitle = !!text;
        if (hasTitle) { if (typeof window.storeRightExpand === 'function') window.storeRightExpand(); }
        else { if (typeof storeRightCollapse === 'function') storeRightCollapse(); }
        $('#bookings-right-title').text(text || '');
        $('#bookings-right-header').toggle(hasTitle);
        $('#bookings-services-panel').toggle(!hasTitle);
        $('#bookings-edit-panel').css('display', hasTitle ? 'flex' : 'none');
        if (!hasTitle) bookingsState.activeForm = null;
        
        $('#impulse-new-booking-btn').toggleClass('active', bookingsState.activeForm === 'booking');
        $('#impulse-new-service-btn').toggleClass('active', bookingsState.activeForm === 'service');
    }

    var BK_MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    var BK_MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    function initBookingsCalendar() {
        var today = new Date();
        var curYear = today.getFullYear(), curMonth = today.getMonth();
        var $scroll = $('#bookings-months-scroll');
        $scroll.empty();

        if (bookingsState.calObserver) { bookingsState.calObserver.disconnect(); bookingsState.calObserver = null; }

        var startYear = today.getFullYear(), startMonth = today.getMonth() - 3;
        if (startMonth < 0) { startYear--; startMonth += 12; }
        var totalMonths = 13;

        for (var i = 0; i < totalMonths; i++) {
            var y = startYear, m = startMonth + i;
            while (m > 11) { m -= 12; y++; }
            var mid = 'bkcal-' + y + '-' + m;
            var isCurrent = (y === curYear && m === curMonth);
            var $block = $('<div>').attr({ id: mid, 'data-bk-year': y, 'data-bk-month': m })
                .css({ marginBottom: '12px' });
            $block.append(
                $('<div>').css({ fontSize:'11px', fontWeight:'600', color: isCurrent ? '#e0e0e0' : '#888', textTransform:'uppercase', letterSpacing:'0.5px', marginBottom:'4px' })
                    .text(BK_MONTHS_SHORT[m] + ' ' + y)
            );
            $block.append(
                $('<div>').addClass('bkcal-grid').css({ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:'2px', fontSize:'10px' })
            );
            $scroll.append($block);
        }

        if ('IntersectionObserver' in window) {
            bookingsState.calObserver = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        var $b = $(entry.target);
                        if (!$b.data('bk-populated')) {
                            $b.data('bk-populated', true);
                            renderCalMonth($b);
                        }
                    }
                });
            }, { root: $scroll[0], rootMargin: '200px' });
            $scroll.children('[id^="bkcal-"]').each(function() {
                bookingsState.calObserver.observe(this);
            });
        } else {
            
            $scroll.children('[id^="bkcal-"]').each(function() {
                renderCalMonth($(this));
            });
        }

        $scroll.off('scroll.bkcal').on('scroll.bkcal', function() {
            bookingsState.calScrollTop = $(this).scrollTop();
        });

        $scroll.off('click.bkcal').on('click.bkcal', '[data-ymd]', function() {
            var ymd = $(this).attr('data-ymd');
            if (bookingsState.filters.date === ymd) {
                bookingsState.filters.date = '';
            } else {
                bookingsState.filters.date = ymd;
            }
            refreshCalHighlights();
            loadBookingsList();
        });

        setTimeout(function() {
            if (bookingsState.calScrollTop !== null) {
                $scroll.scrollTop(bookingsState.calScrollTop);
            } else {
                var $cur = $('#bkcal-' + today.getFullYear() + '-' + today.getMonth());
                if ($cur.length) {
                    $scroll.scrollTop($cur[0].offsetTop - 8);
                }
            }
        }, 50);
    }

    function renderCalMonth($block) {
        var y = parseInt($block.attr('data-bk-year'));
        var m = parseInt($block.attr('data-bk-month'));
        var today = new Date();
        var firstDay = new Date(y, m, 1).getDay();
        var daysInMonth = new Date(y, m + 1, 0).getDate();
        var selDate = bookingsState.filters.date;
        var html = '';
        
        ['S','M','T','W','T','F','S'].forEach(function(d) {
            html += '<div style="text-align:center;color:#555;padding:2px 0">' + d + '</div>';
        });
        for (var i = 0; i < firstDay; i++) html += '<div></div>';
        for (var day = 1; day <= daysInMonth; day++) {
            var ymd = y + '-' + String(m + 1).padStart(2,'0') + '-' + String(day).padStart(2,'0');
            var isToday = (today.getFullYear() === y && today.getMonth() === m && today.getDate() === day);
            var isSelected = (selDate === ymd);
            var hasBooking = bookingsState.bookingDates.has(ymd);
            var style = 'text-align:center;padding:3px 0;border-radius:3px;cursor:pointer;transition:background 0.1s;';
            if (isSelected) {
                style += 'background:#e0e0e0;color:#1d2327;font-weight:600;';
            } else if (isToday) {
                style += 'color:#fff;font-weight:600;border-bottom:2px solid #fff;' + (hasBooking ? 'background:#2a2e33;' : '');
            } else if (hasBooking) {
                style += 'background:#2a2e33;color:#e0e0e0;';
            } else {
                style += 'color:#888;';
            }
            html += '<div class="bkcal-day" data-ymd="' + ymd + '" style="' + style + '">' + day + '</div>';
        }
        $block.find('.bkcal-grid').html(html);
    }

    function refreshCalHighlights() {
        
        $('#bookings-months-scroll [data-bk-populated]').each(function() {
            renderCalMonth($(this));
        });
    }

    function loadAllBookingDates() {
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_get_bookings_list',
            nonce:  window.Impulse.adminNonce,
            status: 'all',
            search: '',
            date:   ''
        }, function(res) {
            if (res.success) {
                var dates = new Set();
                (res.data.bookings || []).forEach(function(b) {
                    if (b.date_ymd) dates.add(b.date_ymd);
                    else if (b.start_time) dates.add(b.start_time.split(' ')[0]);
                });
                bookingsState.bookingDates = dates;
                refreshCalHighlights();
            }
        });
    }

    var inquiriesState = { loaded: false, loading: false };
    function loadInquiries() {
        if (inquiriesState.loading) return;
        inquiriesState.loading = true;
        var $l = $('#inquiries-list');
        $l.html('<div class="impulse-loading">Loading inquiries...</div>');
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_get_form_submissions',
            nonce:  window.Impulse.adminNonce
        }, function(res) {
            inquiriesState.loading = false;
            if (res.success) { renderInquiries(res.data.submissions || []); $('#inquiries-count').text(res.data.count || 0); }
            else { $l.html('<div style="padding:20px;text-align:center;color:#555;font-size:11px">Error loading inquiries</div>'); }
        }).fail(function() {
            inquiriesState.loading = false;
            $l.html('<div style="padding:20px;text-align:center;color:#555;font-size:11px">Connection error</div>');
        });
    }
    function renderInquiries(list) {
        var $l = $('#inquiries-list');
        function esc(s){ return $('<div>').text(s == null ? '' : String(s)).html(); }
        if (!list.length) { $l.html('<div style="padding:48px;text-align:center;color:#555;font-size:12px">No inquiries yet. Submissions from your forms will appear here.</div>'); return; }
        var html = '';
        list.forEach(function(s) {
            var when = '';
            if (s.created_at) { var d = new Date(s.created_at.replace(' ', 'T')); if (!isNaN(d)) when = d.toLocaleString('en-US', { month:'short', day:'numeric', year:'numeric', hour:'numeric', minute:'2-digit' }); }
            html += '<div style="background:#1a1d21;border:1px solid #2a2e33;border-radius:8px;padding:14px 16px;margin-bottom:10px">';
            html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid #2a2e33">';
            html += '<span style="font-size:12px;font-weight:600;color:#e0e0e0">' + esc(s.form_name || 'Submission') + '</span><span style="font-size:11px;color:#777">' + esc(when) + '</span></div>';
            html += '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:8px 20px">';
            var f = s.fields || {};
            Object.keys(f).forEach(function(k) {
                var v = f[k]; if (Array.isArray(v)) v = v.join(', '); v = (v == null ? '' : String(v)); if (!v.trim()) return;
                var label = k.replace(/[_-]/g, ' ').replace(/\b\w/g, function(c){ return c.toUpperCase(); });
                var vh = esc(v);
                if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v)) vh = '<a href="mailto:' + esc(v) + '" style="color:#cdb87a">' + vh + '</a>';
                else if (/^[0-9()+\-.\s]{7,}$/.test(v)) vh = '<a href="tel:' + esc(v.replace(/[^0-9+]/g, '')) + '" style="color:#cdb87a">' + vh + '</a>';
                var full = v.length > 60 ? 'grid-column:1/-1;' : '';
                html += '<div style="font-size:12px;' + full + '"><div style="color:#777;font-size:10px;text-transform:uppercase;letter-spacing:.4px">' + esc(label) + '</div><div style="color:#e0e0e0;word-break:break-word">' + vh + '</div></div>';
            });
            html += '</div></div>';
        });
        $l.html(html);
    }

    function loadBookingsList() {
        if (bookingsState.loading) return;
        bookingsState.loading = true;
        var $list = $('#bookings-list');
        $list.html('<div class="impulse-loading">Loading...</div>');
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_get_bookings_list',
            nonce:  window.Impulse.adminNonce,
            status: bookingsState.filters.status,
            search: bookingsState.filters.search,
            date:   bookingsState.filters.date
        }, function(res) {
            bookingsState.loading = false;
            if (res.success) {
                bookingsState.bookings = res.data.bookings || [];
                renderBookingsList();
                updateBookingsStats(res.data.stats || {});
            } else {
                $list.html('<div style="padding:20px;text-align:center;color:#555;font-size:11px">Error loading bookings</div>');
            }
        }).fail(function() {
            bookingsState.loading = false;
            $list.html('<div style="padding:20px;text-align:center;color:#555;font-size:11px">Connection error</div>');
        });
    }

    function renderBookingsList() {
        var $list = $('#bookings-list');
        var bookings = bookingsState.bookings;
        if (!bookings.length) {
            var msg = bookingsState.filters.status === 'upcoming'
                ? 'No upcoming bookings'
                : 'No bookings found';
            $list.html('<div style="display:flex;align-items:center;justify-content:center;height:100%;min-height:220px"><svg viewBox="0 0 24 24" width="48" height="48" color="currentColor" style="opacity:0.12"><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>');
            return;
        }
        var statusColors = { pending: '#888', confirmed: '#e0e0e0', completed: '#666', cancelled: '#555', no_show: '#555' };
        var html = '';
        bookings.forEach(function(b) {
            var isSelected = bookingsState.selected === b.id;
            var sc = statusColors[b.status] || '#888';
            html += '<div class="impulse-booking-row' + (isSelected ? ' selected' : '') + '" data-booking-id="' + b.id + '" style="display:flex;align-items:center;gap:10px;padding:10px 30px;border-bottom:1px solid #1a1d21;cursor:pointer">';
            
            html += '<div style="width:8px;height:8px;border-radius:50%;background:' + sc + ';flex-shrink:0"></div>';
            
            html += '<div style="flex-shrink:0;width:56px">';
            html += '<div style="font-size:10px;font-weight:600;color:#e0e0e0">' + escapeHtml(b.date_label) + '</div>';
            html += '<div style="font-size:10px;color:#888">' + escapeHtml(b.time_label) + '</div>';
            html += '</div>';
            
            html += '<div style="flex:1;min-width:0">';
            html += '<div style="font-size:11px;color:#e0e0e0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(b.customer_name) + '</div>';
            html += '<div style="font-size:10px;color:#888;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(b.service_name || 'Service') + '</div>';
            html += '</div>';

            if (b.repeats) {
                html += '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="#888" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0" aria-label="Repeating"><path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/></svg>';
            }
            
            html += '<div style="font-size:10px;color:' + sc + ';flex-shrink:0;text-transform:capitalize">' + escapeHtml(b.status) + '</div>';
            html += '</div>';
        });
        $list.html(html);
    }

    $(document).on('click', '.impulse-booking-row', function() {
        var id = parseInt($(this).data('booking-id'));
        if (bookingsState.selected === id) return;
        bookingsState.selected = id;
        $('.impulse-booking-row').removeClass('selected');
        $(this).addClass('selected');
        loadBookingDetail(id);
    });

    function loadBookingDetail(id) {
        setBookingsRightTitle('Loading...');
        $('#impulse-bookings-edit').html('<div class="impulse-loading" style="padding:20px">Loading...</div>');
        $.post(window.Impulse.products.ajaxurl, {
            action:     'instinctor_get_booking',
            nonce:      window.Impulse.adminNonce,
            booking_id: id
        }, function(res) {
            if (res.success) {
                renderBookingDetail(res.data);
            } else {
                $('#impulse-bookings-edit').html('<div style="padding:20px;color:#555;font-size:11px">Error loading booking</div>');
            }
        });
    }

    function renderBookingDetail(b) {
        if (typeof window.storeRightExpand === 'function') window.storeRightExpand();
        setBookingsRightTitle('Booking Details');
        var statusColors = { pending: '#888', confirmed: '#e0e0e0', completed: '#666', cancelled: '#555', no_show: '#555' };
        var sc = statusColors[b.status] || '#888';
        var html = '<div style="padding:8px 12px 16px">';

        html += '<div class="impulse-detail-section" style="display:flex;align-items:center;justify-content:space-between">';
        html += '<span style="font-size:11px;color:#aaa">Booking #' + b.id + '</span>';
        html += '<span style="font-size:11px;color:' + sc + ';font-weight:500;text-transform:capitalize">' + escapeHtml(b.status) + '</span>';
        html += '</div>';

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Service</label>';
        html += '<div style="font-size:12px;color:#e0e0e0">' + escapeHtml(b.service_name || '—') + '</div>';
        html += '<div style="display:flex;gap:8px;margin-top:6px">';
        html += '<div style="flex:1"><span style="font-size:11px;color:#aaa">Date</span><div style="font-size:11px;color:#e0e0e0;margin-top:2px">' + escapeHtml(b.date) + '</div></div>';
        html += '<div style="flex:1"><span style="font-size:11px;color:#aaa">Time</span><div style="font-size:11px;color:#e0e0e0;margin-top:2px">' + escapeHtml(b.time) + '</div></div>';
        html += '</div></div>';

        if (b.series) {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Repeating</label>';
            html += '<div style="font-size:12px;color:#e0e0e0">' + escapeHtml(b.series.label) + '</div>';
            var rem = parseInt(b.series.remaining) || 0;
            var remTxt = b.series.status !== 'active'
                ? 'Stopped'
                : (rem === 0 ? 'No visits ahead' : (rem === 1 ? '1 visit ahead' : rem + ' visits ahead'));
            html += '<div style="font-size:11px;color:#888;margin-top:2px">' + escapeHtml(remTxt) + '</div>';
            html += '</div>';
        }

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Customer</label>';
        html += '<div style="font-size:11px;color:#e0e0e0">' + escapeHtml(b.customer_name) + '</div>';
        if (b.email) html += '<a href="mailto:' + escapeHtml(b.email) + '" style="font-size:11px;color:#888;text-decoration:none">' + escapeHtml(b.email) + '</a>';
        if (b.phone) html += '<div style="font-size:11px;color:#666;margin-top:1px">' + escapeHtml(b.phone) + '</div>';
        html += '</div>';

        if (staffState.staff && staffState.staff.length) {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Assigned to</label>';
            html += '<select id="bk-staff-select" data-booking-id="' + b.id + '" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:6px 8px;box-sizing:border-box;outline:none">';
            html += '<option value="">Unassigned</option>';
            staffState.staff.forEach(function(s) {
                var sel = (b.staff_id && b.staff_id == s.id) ? ' selected' : '';
                html += '<option value="' + s.id + '"' + sel + '>' + escapeHtml(s.name) + (s.title ? ' (' + escapeHtml(s.title) + ')' : '') + '</option>';
            });
            html += '</select>';
            html += '</div>';
        }

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Notes</label>';
        if (b.note) html += '<div style="font-size:11px;color:#888;margin-bottom:6px;line-height:1.5">' + escapeHtml(b.note) + '</div>';
        html += '<textarea id="bk-admin-note" placeholder="Add admin note..." style="width:100%;min-height:54px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:6px 8px;box-sizing:border-box;resize:vertical;font-family:inherit;line-height:1.5"></textarea>';
        html += '</div>';

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:6px">Actions</label>';
        html += '<div style="display:flex;flex-direction:column;gap:4px">';
        if (b.status === 'pending') {
            html += '<button type="button" class="impulse-btn-sm bk-action" data-action="confirmed" data-id="' + b.id + '" style="width:100%;background:#e0e0e0;color:#1d2327;border-color:#e0e0e0">Confirm Booking</button>';
        }
        if (b.status === 'confirmed') {
            html += '<button type="button" class="impulse-btn-sm bk-action" data-action="completed" data-id="' + b.id + '" style="width:100%">Mark Completed</button>';
            html += '<button type="button" class="impulse-btn-sm bk-action" data-action="no_show" data-id="' + b.id + '" style="width:100%">No Show</button>';
        }
        if (b.status !== 'cancelled' && b.status !== 'completed') {
            html += '<button type="button" class="impulse-btn-sm bk-action" data-action="cancelled" data-id="' + b.id + '" style="width:100%;color:#555">Cancel Booking</button>';
        }

        if (b.series && b.series.status === 'active' && (parseInt(b.series.remaining) || 0) > 0) {
            html += '<button type="button" class="impulse-btn-sm bk-stop-series" data-series-id="' + b.series.id + '" data-booking-id="' + b.id + '" style="width:100%;color:#555">Stop Repeating</button>';
        }
        html += '</div>';
        if (b.order_id) html += '<div style="font-size:10px;color:#555;margin-top:6px">Order #' + b.order_id + '</div>';
        html += '</div>';

        html += '</div>';
        $('#impulse-bookings-edit').html(html);
    }

    $(document).on('click', '.bk-stop-series', function() {
        var $btn = $(this);
        var seriesId = parseInt($btn.data('series-id')) || 0;
        var bookingId = parseInt($btn.data('booking-id')) || 0;
        if (!seriesId) return;
        if (!window.impulseConfirm('Stop this repeating appointment? Visits already served stay booked; the ones still ahead are cancelled and the client is told.')) return;
        $btn.prop('disabled', true).text('Stopping...');
        $.post(window.Impulse.products.ajaxurl, {
            action:     'instinctor_stop_booking_series',
            nonce:      window.Impulse.adminNonce,
            series_id:  seriesId,
            booking_id: bookingId
        }, function(res) {
            if (res.success) {
                if (typeof showToast === 'function') showToast((res.data && res.data.message) || 'Stopped');
                loadBookingsList();
                if (bookingId) loadBookingDetail(bookingId);
            } else {
                $btn.prop('disabled', false).text('Stop Repeating');
                if (typeof showToast === 'function') showToast((res.data && res.data.message) || 'Could not stop that schedule', 'error');
            }
        }).fail(function() {
            $btn.prop('disabled', false).text('Stop Repeating');
            if (typeof showToast === 'function') showToast('Connection error', 'error');
        });
    });

    $(document).on('change', '#bk-staff-select', function() {
        var $sel = $(this);
        var bookingId = parseInt($sel.data('booking-id')) || 0;
        var staffId = parseInt($sel.val()) || 0;
        if (!bookingId) return;
        $sel.prop('disabled', true);
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_update_booking_staff',
            nonce: window.Impulse.adminNonce,
            booking_id: bookingId,
            staff_id: staffId
        }, function(res) {
            $sel.prop('disabled', false);
            if (res && res.success) {
                if (typeof showToast === 'function') showToast(staffId ? 'Assigned' : 'Unassigned');
            } else {
                if (typeof showToast === 'function') showToast((res && res.data && res.data.message) || 'Update failed', 'error');
            }
        }).fail(function() {
            $sel.prop('disabled', false);
            if (typeof showToast === 'function') showToast('Update failed', 'error');
        });
    });

    $(document).on('click', '.bk-action', function() {
        var id     = parseInt($(this).data('id'));
        var status = $(this).data('action');
        var $btn   = $(this);
        $btn.prop('disabled', true).text('...');
        $.post(window.Impulse.products.ajaxurl, {
            action:     'instinctor_update_booking_status',
            nonce:      window.Impulse.adminNonce,
            booking_id: id,
            status:     status
        }, function(res) {
            if (res.success) {
                showToast('Booking updated');
                loadBookingDetail(id);
                loadBookingsList();
            } else {
                showToast('Error updating booking', 'error');
                $btn.prop('disabled', false).text($btn.data('action'));
            }
        });
    });

    $(document).on('click', '[data-bstatus]', function() {
        var st = $(this).data('bstatus');
        bookingsState.filters.status = st;
        $('[data-bstatus]').removeClass('active');
        $(this).addClass('active');
        loadBookingsList();
    });

    
    function loadBookingsStats() {
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_get_bookings_stats',
            nonce:  window.Impulse.adminNonce
        }, function(res) {
            if (res.success) updateBookingsStats(res.data);
        });
    }

    function updateBookingsStats(stats) {
        if (stats.today  !== undefined) $('#bstat-today  .impulse-stat-num').text(stats.today);
        if (stats.pending !== undefined) $('#bstat-pending .impulse-stat-num').text(stats.pending);
        if (stats.week   !== undefined) $('#bstat-week   .impulse-stat-num').text(stats.week);
        if (stats.month  !== undefined) $('#bstat-month  .impulse-stat-num').text(stats.month);
    }

    bookingsState.servicesLoaded = false;

    function loadServicesListData() {
        bookingsState.servicesLoaded = true;
        $('#bookings-services-right').html('<div style="padding:8px 12px;font-size:11px;color:#555">Loading...</div>');
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_get_services',
            nonce:  window.Impulse.adminNonce
        }, function(res) {
            if (res.success) {
                bookingsState.services = res.data.services || [];
                renderServicesList();
            } else {
                $('#bookings-services-right').html('<div style="padding:8px 12px;font-size:11px;color:#555">Error</div>');
            }
        });
    }

    function renderServicesList() {
        var $list = $('#bookings-services-right');
        var services = bookingsState.services;
        if (!services.length) {
            $list.html('<div style="padding:8px 12px;font-size:11px;color:#555">No services yet</div>');
            return;
        }
        var html = '';
        services.forEach(function(s) {
            html += '<div class="impulse-service-row" data-service-id="' + s.id + '" style="display:flex;align-items:center;gap:8px;padding:5px 8px;cursor:pointer;border-radius:3px;margin:1px 8px;box-sizing:border-box">';
            html += '<div style="width:6px;height:6px;border-radius:50%;background:' + escapeHtml(s.color || '#555') + ';flex-shrink:0"></div>';
            html += '<div style="flex:1;min-width:0">';
            html += '<div style="font-size:11px;color:#e0e0e0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(s.name) + '</div>';
            html += '<div style="font-size:11px;color:#999">' + s.duration + ' min' + (parseFloat(s.price) > 0 ? ' · $' + parseFloat(s.price).toFixed(2) : '') + '</div>';
            html += '</div>';
            html += '</div>';
        });
        $list.html(html);
    }

    $(document).on('click', '#impulse-new-service-btn, #topbar-add-service', function() {
        if (bookingsState.activeForm === 'service') {
            closeNewBookingPanel();
            return;
        }
        bookingsState.selected = null;
        $('.impulse-booking-row').removeClass('selected').css('background', '');
        bookingsState.activeForm = 'service';
        openServiceForm(null);
    });
    
    $(document).on('click', '.impulse-service-row', function(e) {
        if ($(e.target).closest('button').length) return; 
        var id = parseInt($(this).data('service-id'));
        var s = bookingsState.services.find(function(sv) { return sv.id == id; });
        if (s) {
            bookingsState.selected = null;
            $('.impulse-booking-row').removeClass('selected').css('background', '');
            $('.impulse-service-row').css('background', '');
            $(this).css('background', '#2a2e33');
            openServiceForm(s);
        }
    });

    function openServiceForm(s) {
        setBookingsRightTitle(s ? 'Edit Service' : 'New Service');
        var sv = s || { id: 0, name: '', description: '', duration: 60, buffer_before: 0, buffer_after: 15, price: '', deposit: '', capacity: 1, color: '#555555', status: 'active' };
        var inp = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var fg8 = 'margin-bottom:8px';
        var html = '<div style="padding:8px 12px 16px">';
        html += '<div class="impulse-form-group" style="' + fg8 + '"><label>Name</label><input type="text" id="svc-name" value="' + escapeHtml(sv.name) + '" style="' + inp + '"></div>';
        html += '<div class="impulse-form-group" style="' + fg8 + '"><label>Description</label><textarea id="svc-desc" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:5px 8px;box-sizing:border-box;min-height:50px;resize:vertical;font-family:inherit">' + escapeHtml(sv.description || '') + '</textarea></div>';
        html += '<div class="impulse-form-row" style="' + fg8 + '"><div class="impulse-form-group"><label>Duration (min)</label><input type="text" inputmode="numeric" id="svc-duration" value="' + parseInt(sv.duration) + '" style="' + inp + '"></div>';
        html += '<div class="impulse-form-group"><label>Price</label><input type="text" inputmode="decimal" id="svc-price" value="' + (sv.price || '') + '" placeholder="0.00" style="' + inp + '"></div></div>';
        html += '<div class="impulse-form-row" style="' + fg8 + '"><div class="impulse-form-group"><label>Deposit ($)</label><input type="text" inputmode="decimal" id="svc-deposit" value="' + (sv.deposit || '') + '" placeholder="0.00" style="' + inp + '"></div><div class="impulse-form-group"></div></div>';
        html += '<div class="impulse-form-row" style="' + fg8 + '"><div class="impulse-form-group"><label>Buffer before (min)</label><input type="text" inputmode="numeric" id="svc-buf-before" value="' + parseInt(sv.buffer_before) + '" style="' + inp + '"></div>';
        html += '<div class="impulse-form-group"><label>Buffer after (min)</label><input type="text" inputmode="numeric" id="svc-buf-after" value="' + parseInt(sv.buffer_after) + '" style="' + inp + '"></div></div>';
        var svcColor = sv.color || '#555555';
        html += '<div class="impulse-form-row"><div class="impulse-form-group"><label>Capacity</label><input type="text" inputmode="numeric" id="svc-capacity" value="' + parseInt(sv.capacity) + '" style="' + inp + '"></div>';
        html += '<div class="impulse-form-group"><label>Color</label>';
        html += '<div class="impulse-color-row"><div class="impulse-color-swatch" style="--swatch-color:' + escapeHtml(svcColor) + ';width:26px;height:26px" data-default="' + escapeHtml(svcColor) + '"></div>';
        html += '<input type="hidden" id="svc-color" class="impulse-color-text" value="' + escapeHtml(svcColor) + '">';

        html += '</div></div></div>';
        
        var defAvail = { monday:{open:true,from:'09:00',to:'17:00'}, tuesday:{open:true,from:'09:00',to:'17:00'}, wednesday:{open:true,from:'09:00',to:'17:00'}, thursday:{open:true,from:'09:00',to:'17:00'}, friday:{open:true,from:'09:00',to:'17:00'}, saturday:{open:false,from:'10:00',to:'14:00'}, sunday:{open:false,from:'10:00',to:'14:00'} };
        var avail = sv.availability || defAvail;
        
        if (avail.start !== undefined) {
            var migrDays = { monday:true,tuesday:true,wednesday:true,thursday:true,friday:true,saturday:false,sunday:false };
            var migrated = {};
            ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'].forEach(function(d) {
                migrated[d] = { open: !!(avail.days && avail.days[d] !== undefined ? avail.days[d] : migrDays[d]), from: avail.start || '09:00', to: avail.end || '17:00' };
            });
            avail = migrated;
        }
        var dayKeys   = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
        var dayLabels = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
        html += '<div class="impulse-section-divider" style="margin-top:8px">Availability</div>';
        html += '<div style="margin-top:6px">';
        dayKeys.forEach(function(day, i) {
            var d = avail[day] || { open: i < 5, from: '09:00', to: '17:00' };
            var open = d.open !== false;
            html += '<div class="svc-avail-row' + (open ? '' : ' closed') + '" data-day="' + day + '">';
            html += '<span class="svc-avail-day">' + dayLabels[i] + '</span>';
            html += '<button type="button" class="svc-avail-time-btn" data-role="from" data-day="' + day + '" onclick="svcOpenTimePicker(this)">' + escapeHtml(d.from || '09:00') + '</button>';
            html += '<span class="svc-avail-sep">–</span>';
            html += '<button type="button" class="svc-avail-time-btn" data-role="to" data-day="' + day + '" onclick="svcOpenTimePicker(this)">' + escapeHtml(d.to || '17:00') + '</button>';
            html += '<span style="flex:1"></span>';
            html += '<input type="checkbox" class="svc-avail-open-cb" data-day="' + day + '"' + (open ? ' checked' : '') + ' style="width:14px;height:14px;cursor:pointer;flex-shrink:0" title="Open" onchange="svcToggleDay(this)">';
            html += '</div>';
        });
        html += '</div>';
        html += '<input type="hidden" id="svc-availability" value="">';

        html += '<div style="display:flex;gap:6px;margin-top:12px">';
        if (sv.id) html += '<button type="button" id="svc-cancel" class="impulse-btn-sm" style="color:#555">Cancel</button>';
        html += '<button type="button" id="svc-save" data-id="' + sv.id + '" class="impulse-btn-sm" style="flex:1;background:#3a3f44;color:#e0e0e0;border-color:#555">Save Service</button>';
        html += '</div>';
        if (sv.id) {
            html += '<button type="button" id="svc-delete" data-id="' + sv.id + '" class="impulse-btn-sm" style="width:100%;margin-top:6px;color:#555;border-color:#2a2e33">Delete Service</button>';
        }
        html += '</div>';
        $('#impulse-bookings-edit').html(html);
        syncAvailField();
    }

    $(document).on('click', '#svc-save', function() {
        var id = parseInt($(this).data('id'));
        var name = $('#svc-name').val().trim();
        if (!name) { showToast('Service name required', 'error'); return; }
        var $btn = $(this).prop('disabled', true).text('Saving...');
        $.post(window.Impulse.products.ajaxurl, {
            action:        'instinctor_save_service',
            nonce:         window.Impulse.adminNonce,
            id:            id,
            name:          name,
            description:   $('#svc-desc').val(),
            duration:      $('#svc-duration').val(),
            buffer_before: $('#svc-buf-before').val(),
            buffer_after:  $('#svc-buf-after').val(),
            price:         $('#svc-price').val(),
            deposit:       $('#svc-deposit').val(),
            capacity:      $('#svc-capacity').val(),
            color:         $('#svc-color').val(),
            availability:  $('#svc-availability').val(),
            status:        'active'
        }, function(res) {
            $btn.prop('disabled', false).text('Save Service');
            if (res.success) {
                showToast('Service saved');
                bookingsState.servicesLoaded = false;
                loadServicesListData();
                setBookingsRightTitle('');
                $('#impulse-bookings-edit').html('');
            } else {
                showToast(res.data || 'Error saving service', 'error');
            }
        });
    });

    function syncAvailField() {
        var data = {};
        $('#impulse-bookings-edit .svc-avail-row').each(function() {
            var day  = $(this).data('day');
            var open = $(this).find('.svc-avail-open-cb').prop('checked');
            var from = $(this).find('.svc-avail-time-btn[data-role="from"]').text().trim();
            var to   = $(this).find('.svc-avail-time-btn[data-role="to"]').text().trim();
            data[day] = { open: open, from: from, to: to };
        });
        $('#svc-availability').val(JSON.stringify(data));
    }

    window.svcToggleDay = function(cb) {
        var $row = $(cb).closest('.svc-avail-row');
        $row.toggleClass('closed', !cb.checked);
        syncAvailField();
    };

    var _svcTpBtn = null;

    window.svcOpenTimePicker = function(btn) {
        
        $('#svc-timepicker-popup').remove();
        if (_svcTpBtn === btn && _svcTpBtn !== null) { _svcTpBtn = null; return; }
        _svcTpBtn = btn;

        var parts = ($(btn).text().trim() || '09:00').split(':');
        var curH = parseInt(parts[0]) || 9;
        var curM = Math.round((parseInt(parts[1]) || 0) / 15) * 15;
        if (curM >= 60) curM = 45;

        var rect = btn.getBoundingClientRect();

        var $pop = $('<div id="svc-timepicker-popup"></div>').css({
            position:'fixed', top: rect.bottom + 4, right: (window.innerWidth - rect.right),
            width: 200, background:'#1a1d21', border:'1px solid #3a3f44',
            borderRadius:'4px', boxShadow:'0 4px 16px rgba(0,0,0,0.5)',
            padding:'10px', boxSizing:'border-box', zIndex:1000030
        });
        $pop.on('click', function(e) { e.stopPropagation(); });

        $pop.append($('<div>Hour</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $hGrid = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(6,1fr)', gap:'3px', marginBottom:'8px' });
        for (var hh = 0; hh < 24; hh++) {
            (function(h) {
                var sel = (h === curH);
                var $b = $('<button type="button">' + (h < 10 ? '0'+h : h) + '</button>').css(nbTimeGridBtn(sel));
                if (sel) $b.addClass('svc-tp-hsel');
                $b.on('click', function() {
                    $hGrid.find('.svc-tp-hsel').each(function() { $(this).css(nbTimeGridBtn(false)).removeClass('svc-tp-hsel'); });
                    $(this).css(nbTimeGridBtn(true)).addClass('svc-tp-hsel');
                    curH = h;
                    svcTpApplyIfComplete();
                });
                $hGrid.append($b);
            })(hh);
        }
        $pop.append($hGrid);

        $pop.append($('<div>Minute</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $mRow = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'3px' });
        [0,15,30,45].forEach(function(m) {
            var sel = (m === curM);
            var $b = $('<button type="button">:' + (m < 10 ? '0'+m : m) + '</button>').css(nbTimeGridBtn(sel));
            if (sel) $b.addClass('svc-tp-msel');
            $b.on('click', function() {
                $mRow.find('.svc-tp-msel').each(function() { $(this).css(nbTimeGridBtn(false)).removeClass('svc-tp-msel'); });
                $(this).css(nbTimeGridBtn(true)).addClass('svc-tp-msel');
                curM = m;
                svcTpApplyIfComplete();
            });
            $mRow.append($b);
        });
        $pop.append($mRow);

        $('body').append($pop);

        var popH = $pop.outerHeight(true) || 160;
        if (rect.bottom + popH + 4 > window.innerHeight - 8) $pop.css('top', rect.top - popH - 4);

        function svcTpApplyIfComplete() {
            
            var val = (curH < 10 ? '0'+curH : curH) + ':' + (curM < 10 ? '0'+curM : curM);
            $(_svcTpBtn).text(val);
            syncAvailField();
            $('#svc-timepicker-popup').remove();
            _svcTpBtn = null;
        }
    };

    $(document).on('click.svctimepicker', function(e) {
        if (!$(e.target).closest('#svc-timepicker-popup, .svc-avail-time-btn').length) {
            $('#svc-timepicker-popup').remove();
            _svcTpBtn = null;
        }
    });

    $(document).on('click', '#svc-cancel', function() {
        bookingsState.selected = null;
        setBookingsRightTitle('');
        $('#impulse-bookings-edit').html('');
    });

    $(document).on('click', '#svc-delete', function() {
        var id = parseInt($(this).data('id'));
        if (!id || !window.impulseConfirm('Delete this service? This cannot be undone.')) return;
        var $btn = $(this).prop('disabled', true).text('Deleting...');
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_delete_service',
            nonce:  window.Impulse.adminNonce,
            id:     id
        }, function(res) {
            if (res.success) {
                showToast('Service deleted');
                bookingsState.servicesLoaded = false;
                loadServicesListData();
                setBookingsRightTitle('');
                $('#impulse-bookings-edit').html('');
            } else {
                showToast(res.data || 'Error', 'error');
                $btn.prop('disabled', false).text('Delete Service');
            }
        });
    });

    var staffState = { loaded: false, staff: [], services: [] };

    function staffAvatarBg(s) {
        return s.photo_url ? ('#2a2e33 center/cover url(' + escapeHtml(s.photo_url) + ')') : escapeHtml(s.calendar_color || '#7E946C');
    }

    function loadStaffListData() {
        staffState.loaded = true;
        $('#staff-list-left').html('<div style="padding:8px 12px;font-size:11px;color:#555">Loading...</div>');
        $.post(window.Impulse.products.ajaxurl, { action: 'instinctor_get_staff', nonce: window.Impulse.adminNonce }, function(res) {
            if (res.success) { staffState.staff = res.data.staff || []; staffState.services = res.data.services || []; renderStaffList(); }
            else { $('#staff-list-left').html('<div style="padding:8px 12px;font-size:11px;color:#555">Error</div>'); }
        });
    }

    function renderStaffList() {
        var $l = $('#staff-list-left');
        if (!staffState.staff.length) { $l.html('<div style="padding:10px 12px;font-size:11px;color:#555">No staff yet. Add your first team member.</div>'); return; }
        var h = '';
        staffState.staff.forEach(function(s) {
            h += '<div class="impulse-staff-row" data-staff-id="' + s.id + '" style="display:flex;align-items:center;gap:8px;padding:6px 10px;cursor:pointer;border-radius:3px;margin:1px 6px">';
            h += '<div style="width:24px;height:24px;border-radius:50%;flex-shrink:0;background:' + staffAvatarBg(s) + '"></div>';
            h += '<div style="flex:1;min-width:0"><div style="font-size:11px;color:#e0e0e0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(s.name) + (s.bookable ? '' : ' <span style="color:#777">(hidden)</span>') + '</div>';
            h += '<div style="font-size:11px;color:#999;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(s.title || '') + '</div></div></div>';
        });
        $l.html(h);
    }

    $(document).on('click', '#impulse-new-staff-btn', function() { $('.impulse-staff-row').css('background', ''); openStaffForm(null); });
    $(document).on('click', '.impulse-staff-row', function() {
        var id = parseInt($(this).data('staff-id'));
        var s = staffState.staff.find(function(x) { return x.id == id; });
        if (s) { $('.impulse-staff-row').css('background', ''); $(this).css('background', '#2a2e33'); openStaffForm(s); }
    });

    function openStaffForm(s) {
        var st = s || { id: 0, name: '', title: '', commission_rate: 0, calendar_color: '#7E946C', bookable: true, photo_url: '', hours: null, service_ids: [] };
        var inp = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var fg8 = 'margin-bottom:8px';
        var h = '<div style="padding:12px 16px 18px;max-width:540px">';
        h += '<div style="display:flex;gap:12px;' + fg8 + '"><div style="flex-shrink:0"><div id="staff-photo-prev" style="width:56px;height:56px;border-radius:50%;overflow:hidden;background:' + staffAvatarBg(st) + ';cursor:pointer" title="Choose photo"></div></div>';
        h += '<div style="flex:1;min-width:0"><div class="impulse-form-group" style="margin-bottom:6px"><label>Name</label><input type="text" id="staff-name" value="' + escapeHtml(st.name) + '" style="' + inp + '"></div>';
        h += '<div class="impulse-form-group"><label>Title</label><input type="text" id="staff-title" value="' + escapeHtml(st.title || '') + '" placeholder="e.g. Senior Stylist" style="' + inp + '"></div></div></div>';
        h += '<input type="hidden" id="staff-photo-url" value="' + escapeHtml(st.photo_url || '') + '">';
        h += '<div class="impulse-form-row" style="' + fg8 + '"><div class="impulse-form-group"><label>Commission (%)</label><input type="text" inputmode="decimal" id="staff-commission" value="' + (st.commission_rate || 0) + '" style="' + inp + '"></div>';
        h += '<div class="impulse-form-group"><label>Calendar color</label><div class="impulse-color-row"><div class="impulse-color-swatch" style="--swatch-color:' + escapeHtml(st.calendar_color || '#7E946C') + ';width:26px;height:26px" data-default="' + escapeHtml(st.calendar_color || '#7E946C') + '"></div><input type="hidden" id="staff-color" class="impulse-color-text" value="' + escapeHtml(st.calendar_color || '#7E946C') + '"></div></div></div>';
        h += '<label style="display:flex;align-items:center;gap:8px;font-size:11px;color:#e0e0e0;' + fg8 + '"><input type="checkbox" id="staff-bookable"' + (st.bookable !== false ? ' checked' : '') + ' style="width:14px;height:14px">Bookable online</label>';
        var defH = { monday:{open:true,from:'09:00',to:'17:00'},tuesday:{open:true,from:'09:00',to:'17:00'},wednesday:{open:true,from:'09:00',to:'17:00'},thursday:{open:true,from:'09:00',to:'17:00'},friday:{open:true,from:'09:00',to:'17:00'},saturday:{open:false,from:'10:00',to:'14:00'},sunday:{open:false,from:'10:00',to:'14:00'} };
        var hrs = st.hours || defH;
        var dk = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'], dl = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
        h += '<div class="impulse-section-divider" style="margin-top:8px">Working hours</div><div style="margin-top:6px">';
        dk.forEach(function(day, i) {
            var d = hrs[day] || { open: i < 5, from: '09:00', to: '17:00' }; var open = d.open !== false;
            h += '<div class="staff-hours-row svc-avail-row' + (open ? '' : ' closed') + '" data-day="' + day + '">';
            h += '<span class="svc-avail-day">' + dl[i] + '</span>';
            h += '<button type="button" class="staff-hours-time-btn svc-avail-time-btn" data-role="from" onclick="staffOpenTimePicker(this)">' + escapeHtml(d.from || '09:00') + '</button>';
            h += '<span class="svc-avail-sep">–</span>';
            h += '<button type="button" class="staff-hours-time-btn svc-avail-time-btn" data-role="to" onclick="staffOpenTimePicker(this)">' + escapeHtml(d.to || '17:00') + '</button>';
            h += '<span style="flex:1"></span>';
            h += '<input type="checkbox" class="staff-hours-open-cb" data-day="' + day + '"' + (open ? ' checked' : '') + ' style="width:14px;height:14px;cursor:pointer;flex-shrink:0" onchange="staffToggleDay(this)">';
            h += '</div>';
        });
        h += '</div><input type="hidden" id="staff-hours" value="">';
        if (staffState.services.length) {
            h += '<div class="impulse-section-divider" style="margin-top:10px">Services performed</div>';
            h += '<div style="font-size:11px;color:#777;margin:4px 0 6px">Leave all unchecked = performs every service.</div><div style="display:flex;flex-direction:column;gap:3px">';
            staffState.services.forEach(function(sv) {
                var ck = (st.service_ids || []).indexOf(sv.id) !== -1;
                h += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#e0e0e0"><input type="checkbox" class="staff-svc-cb" value="' + sv.id + '"' + (ck ? ' checked' : '') + ' style="width:14px;height:14px">' + escapeHtml(sv.name) + '</label>';
            });
            h += '</div>';
        }
        h += '<div style="display:flex;gap:6px;margin-top:14px">';
        if (st.id) h += '<button type="button" id="staff-cancel" class="impulse-btn-sm" style="color:#555">Cancel</button>';
        h += '<button type="button" id="staff-save" data-id="' + st.id + '" class="impulse-btn-sm" style="flex:1;background:#3a3f44;color:#e0e0e0;border-color:#555">Save</button></div>';
        if (st.id) h += '<button type="button" id="staff-delete" data-id="' + st.id + '" class="impulse-btn-sm" style="width:100%;margin-top:6px;color:#555;border-color:#2a2e33">Delete</button>';
        h += '</div>';
        $('#staff-form-right').html(h);
        syncStaffHours();
    }

    $(document).on('click', '#staff-photo-prev', function() {
        if (typeof openImglibPicker === 'function') {
            openImglibPicker({ label: 'Select Staff Photo', simple: true }, function(att) {
                if (!att || !att.url) return;
                $('#staff-photo-url').val(att.url);
                $('#staff-photo-prev').css('background', '#2a2e33 center/cover url(' + att.url + ')');
            });
        }
    });

    function syncStaffHours() {
        var data = {};
        $('#staff-form-right .staff-hours-row').each(function() {
            var day = $(this).data('day');
            data[day] = {
                open: $(this).find('.staff-hours-open-cb').prop('checked'),
                from: $(this).find('.staff-hours-time-btn[data-role="from"]').text().trim(),
                to:   $(this).find('.staff-hours-time-btn[data-role="to"]').text().trim()
            };
        });
        $('#staff-hours').val(JSON.stringify(data));
    }
    window.staffToggleDay = function(cb) { $(cb).closest('.staff-hours-row').toggleClass('closed', !cb.checked); syncStaffHours(); };

    var _staffTpBtn = null;
    window.staffOpenTimePicker = function(btn) {
        $('#staff-timepicker-popup').remove();
        if (_staffTpBtn === btn && _staffTpBtn !== null) { _staffTpBtn = null; return; }
        _staffTpBtn = btn;
        var parts = ($(btn).text().trim() || '09:00').split(':');
        var curH = parseInt(parts[0]) || 9; var curM = Math.round((parseInt(parts[1]) || 0) / 15) * 15; if (curM >= 60) curM = 45;
        var rect = btn.getBoundingClientRect();
        var $pop = $('<div id="staff-timepicker-popup"></div>').css({ position:'fixed', top: rect.bottom + 4, right: (window.innerWidth - rect.right), width: 200, background:'#1a1d21', border:'1px solid #3a3f44', borderRadius:'4px', boxShadow:'0 4px 16px rgba(0,0,0,0.5)', padding:'10px', boxSizing:'border-box', zIndex:1000030 });
        $pop.on('click', function(e) { e.stopPropagation(); });
        function apply() { var val = (curH < 10 ? '0'+curH : curH) + ':' + (curM < 10 ? '0'+curM : curM); $(_staffTpBtn).text(val); syncStaffHours(); $('#staff-timepicker-popup').remove(); _staffTpBtn = null; }
        $pop.append($('<div>Hour</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $hGrid = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(6,1fr)', gap:'3px', marginBottom:'8px' });
        for (var hh = 0; hh < 24; hh++) { (function(hn) { var sel = (hn === curH); var $b = $('<button type="button">' + (hn < 10 ? '0'+hn : hn) + '</button>').css(nbTimeGridBtn(sel)); if (sel) $b.addClass('staff-tp-hsel'); $b.on('click', function() { $hGrid.find('.staff-tp-hsel').each(function() { $(this).css(nbTimeGridBtn(false)).removeClass('staff-tp-hsel'); }); $(this).css(nbTimeGridBtn(true)).addClass('staff-tp-hsel'); curH = hn; apply(); }); $hGrid.append($b); })(hh); }
        $pop.append($hGrid);
        $pop.append($('<div>Minute</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $mRow = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'3px' });
        [0,15,30,45].forEach(function(m) { var sel = (m === curM); var $b = $('<button type="button">:' + (m < 10 ? '0'+m : m) + '</button>').css(nbTimeGridBtn(sel)); if (sel) $b.addClass('staff-tp-msel'); $b.on('click', function() { $mRow.find('.staff-tp-msel').each(function() { $(this).css(nbTimeGridBtn(false)).removeClass('staff-tp-msel'); }); $(this).css(nbTimeGridBtn(true)).addClass('staff-tp-msel'); curM = m; apply(); }); $mRow.append($b); });
        $pop.append($mRow);
        $('body').append($pop);
        var popH = $pop.outerHeight(true) || 160; if (rect.bottom + popH + 4 > window.innerHeight - 8) $pop.css('top', rect.top - popH - 4);
    };
    $(document).on('click.stafftimepicker', function(e) { if (!$(e.target).closest('#staff-timepicker-popup, .staff-hours-time-btn').length) { $('#staff-timepicker-popup').remove(); _staffTpBtn = null; } });

    $(document).on('click', '#staff-cancel', function() { $('#staff-form-right').html('<div style="padding:20px;font-size:11px;color:#555">Select a team member, or add one.</div>'); $('.impulse-staff-row').css('background', ''); });

    $(document).on('click', '#staff-save', function() {
        var id = parseInt($(this).data('id')) || 0;
        var name = $('#staff-name').val().trim();
        if (!name) { showToast('Staff name required', 'error'); return; }
        var svcIds = $('#staff-form-right .staff-svc-cb:checked').map(function() { return $(this).val(); }).get().join(',');
        var $btn = $(this).prop('disabled', true).text('Saving...');
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_save_staff', nonce: window.Impulse.adminNonce, id: id,
            name: name, title: $('#staff-title').val(), commission_rate: $('#staff-commission').val(),
            calendar_color: $('#staff-color').val(), bookable: $('#staff-bookable').prop('checked') ? 1 : 0,
            photo_url: $('#staff-photo-url').val(), hours: $('#staff-hours').val(), service_ids: svcIds
        }, function(res) {
            $btn.prop('disabled', false).text('Save');
            if (res.success) { showToast('Staff saved'); staffState.loaded = false; loadStaffListData(); $('#staff-form-right').html('<div style="padding:20px;font-size:11px;color:#555">Select a team member, or add one.</div>'); }
            else { showToast(res.data || 'Error saving staff', 'error'); }
        });
    });

    $(document).on('click', '#staff-delete', function() {
        var id = parseInt($(this).data('id'));
        if (!id || !window.impulseConfirm('Delete this team member? Their past bookings stay but become unassigned.')) return;
        var $btn = $(this).prop('disabled', true).text('Deleting...');
        $.post(window.Impulse.products.ajaxurl, { action: 'instinctor_delete_staff', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (res.success) { showToast('Staff deleted'); staffState.loaded = false; loadStaffListData(); $('#staff-form-right').html('<div style="padding:20px;font-size:11px;color:#555">Select a team member, or add one.</div>'); }
            else { showToast(res.data || 'Error', 'error'); $btn.prop('disabled', false).text('Delete'); }
        });
    });

    
    function openNewBookingPanel() {
        bookingsState.selected = null;
        $('.impulse-booking-row').removeClass('selected').css('background', '');
        $('.impulse-service-row').css('background', '');

        var services = bookingsState.services.filter(function(s) { return s.status === 'active'; });
        var svcOptions = '<option value="">Select service...</option>';
        services.forEach(function(s) {
            svcOptions += '<option value="' + s.id + '">' + escapeHtml(s.name) + ' (' + s.duration + ' min)</option>';
        });
        var inp = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var fg  = 'margin-bottom:8px';
        var html = '<div style="padding:14px">';
        
        html += '<div style="' + fg + '"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Service</label>';
        html += '<div style="display:flex;gap:6px">';
        html += '<select id="nb-service" style="flex:1;min-width:0;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 6px;box-sizing:border-box">' + svcOptions + '</select>';
        html += '<button type="button" id="nb-add-service" class="impulse-btn-sm" style="height:26px;padding:0 8px;flex-shrink:0;white-space:nowrap">+ Add</button>';
        html += '</div></div>';
        
        html += '<div style="' + fg + '"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Customer Name</label><input type="text" id="nb-name" style="' + inp + '"></div>';
        
        html += '<div style="display:flex;gap:8px;margin-bottom:8px">';
        html += '<div style="flex:1;min-width:0"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Email</label><input type="email" id="nb-email" style="' + inp + '"></div>';
        html += '<div style="flex:1;min-width:0"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Phone</label><input type="text" id="nb-phone" style="' + inp + '"></div>';
        html += '</div>';
        
        html += '<div style="display:flex;gap:8px;margin-bottom:8px">';
        html += '<div style="flex:1;min-width:0"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Date</label>';
        html += '<div id="nb-date-wrap" style="position:relative">';
        html += '<div id="nb-date-display" style="height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#999;font-size:11px;padding:0 8px;display:flex;align-items:center;cursor:pointer;box-sizing:border-box;user-select:none">Select date</div>';
        html += '<input type="hidden" id="nb-date" value="">';
        html += '</div></div>';
        html += '<div style="flex:1;min-width:0"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Time</label>';
        html += '<div id="nb-time-wrap" style="position:relative">';
        html += '<div id="nb-time-display" style="height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#999;font-size:11px;padding:0 8px;display:flex;align-items:center;cursor:pointer;box-sizing:border-box;user-select:none">Select time</div>';
        html += '<input type="hidden" id="nb-hour" value="">';
        html += '<input type="hidden" id="nb-min" value="">';
        html += '<input type="hidden" id="nb-ampm" value="AM">';
        html += '</div></div>';
        html += '</div>';
        
        html += '<div style="' + fg + '"><label style="font-size:11px;color:#888;display:block;margin-bottom:3px">Note</label>';
        html += '<textarea id="nb-note" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:5px 8px;box-sizing:border-box;resize:vertical;min-height:50px;font-family:inherit"></textarea></div>';
        
        html += '<div style="display:flex;gap:6px;margin-top:4px">';
        html += '<button type="button" id="nb-cancel" class="impulse-btn-sm" style="color:#555">Cancel</button>';
        html += '<button type="button" id="nb-submit" class="impulse-btn-sm" style="flex:1;background:#3a3f44;color:#e0e0e0;border-color:#555">Create Booking</button>';
        html += '</div>';
        html += '</div>';

        setBookingsRightTitle('New Booking');
        $('#impulse-bookings-edit').html(html);

        _nbCalDate = new Date();
        _nbCalOpen = false;
        _nbTimeOpen = false;
    }

    function closeNewBookingPanel() {
        nbCloseDatePicker();
        nbCloseTimePicker();
        setBookingsRightTitle('');
        $('#impulse-bookings-edit').html('');
    }

    $(document).on('click', '#topbar-add-booking, #impulse-new-booking-btn', function() {
        if (bookingsState.activeForm === 'booking') {
            closeNewBookingPanel();
            return;
        }
        bookingsState.activeForm = 'booking';
        openNewBookingPanel();
    });

    $(document).on('click', '#nb-cancel', function() {
        closeNewBookingPanel();
    });

    $(document).on('click', '#nb-add-service', function() {
        nbCloseDatePicker();
        nbCloseTimePicker();
        openServiceForm(null);
    });

    var _nbCalDate = new Date();
    var _nbCalOpen = false;

    function nbCloseDatePicker() {
        $('#nb-datepicker-popup').remove();
        _nbCalOpen = false;
    }

    function nbOpenDatePicker() {
        nbCloseDatePicker();
        _nbCalOpen = true;
        var now = _nbCalDate;
        var year = now.getFullYear(), month = now.getMonth();
        var $wrap = $('#nb-date-wrap');
        var rect  = $wrap[0].getBoundingClientRect();

        var popup = buildNbCalPopup(year, month);
        popup.css({ position: 'fixed', top: rect.bottom + 4, right: (window.innerWidth - rect.right), width: 220, zIndex: 1000030 });
        $('body').append(popup);

        var popH = popup.outerHeight();
        if (rect.bottom + popH + 4 > window.innerHeight - 8) {
            popup.css('top', rect.top - popH - 4);
        }
    }

    function buildNbCalPopup(year, month) {
        var DAYS = ['S','M','T','W','T','F','S'];
        var MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        var selected = $('#nb-date').val();

        var $pop = $('<div id="nb-datepicker-popup" style="background:#1a1d21;border:1px solid #3a3f44;border-radius:4px;box-shadow:0 4px 16px rgba(0,0,0,0.5);padding:10px;box-sizing:border-box"></div>');
        $pop.on('click', function(e) { e.stopPropagation(); });

        var $hdr = $('<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px"></div>');
        var $prev = $('<button type="button" style="background:none;border:none;color:#888;cursor:pointer;padding:2px 6px;font-size:13px">&#8249;</button>');
        var $next = $('<button type="button" style="background:none;border:none;color:#888;cursor:pointer;padding:2px 6px;font-size:13px">&#8250;</button>');
        var $mo   = $('<span style="font-size:11px;font-weight:600;color:#e0e0e0">' + MONTHS[month] + ' ' + year + '</span>');
        $hdr.append($prev).append($mo).append($next);
        $pop.append($hdr);

        $prev.on('click', function(e) { e.stopPropagation(); month--; if (month < 0) { month = 11; year--; } _nbCalDate = new Date(year, month, 1); $('#nb-datepicker-popup').replaceWith(buildNbCalPopup(year, month)); });
        $next.on('click', function(e) { e.stopPropagation(); month++; if (month > 11) { month = 0; year++; } _nbCalDate = new Date(year, month, 1); $('#nb-datepicker-popup').replaceWith(buildNbCalPopup(year, month)); });

        var $grid = $('<div style="display:grid;grid-template-columns:repeat(7,1fr);gap:2px;text-align:center"></div>');
        DAYS.forEach(function(d) { $grid.append('<div style="font-size:9px;color:#555;padding:2px 0">' + d + '</div>'); });

        var firstDay = new Date(year, month, 1).getDay();
        for (var i = 0; i < firstDay; i++) $grid.append('<div></div>');

        var daysInMonth = new Date(year, month + 1, 0).getDate();
        for (var d = 1; d <= daysInMonth; d++) {
            var mm = ('0' + (month + 1)).slice(-2);
            var dd = ('0' + d).slice(-2);
            var val = year + '-' + mm + '-' + dd;
            var isSel = (val === selected);
            var $day = $('<div data-val="' + val + '" style="font-size:10px;padding:3px 2px;border-radius:3px;cursor:pointer;text-align:center;' + (isSel ? 'background:#3a3f44;color:#fff' : 'color:#999') + '">' + d + '</div>');
            $day.on('mouseenter', function() { if (!$(this).hasClass('nb-sel')) $(this).css({ background: '#2a2e33', color: '#e0e0e0' }); });
            $day.on('mouseleave', function() { if (!$(this).hasClass('nb-sel')) $(this).css({ background: '', color: '#999' }); });
            $day.on('click', function(e) {
                e.stopPropagation();
                var v = $(this).data('val');
                var parts = v.split('-');
                var disp = (parseInt(parts[1])) + '/' + parseInt(parts[2]) + '/' + parts[0];
                $('#nb-date').val(v);
                $('#nb-date-display').text(disp).css('color', '#e0e0e0');
                nbCloseDatePicker();
            });
            if (isSel) $day.addClass('nb-sel');
            $grid.append($day);
        }
        $pop.append($grid);
        return $pop;
    }

    $(document).on('click', '#nb-date-display', function(e) {
        e.stopPropagation();
        if (_nbCalOpen) { nbCloseDatePicker(); } else { nbOpenDatePicker(); }
    });
    $(document).on('click.nbcal', function(e) {
        if (_nbCalOpen && !$(e.target).closest('#nb-datepicker-popup, #nb-date-display').length) {
            nbCloseDatePicker();
        }
    });

    var _nbTimeOpen = false;

    function nbCloseTimePicker() {
        $('#nb-timepicker-popup').remove();
        _nbTimeOpen = false;
    }

    function nbOpenTimePicker() {
        nbCloseTimePicker();
        _nbTimeOpen = true;

        var curHour  = parseInt($('#nb-hour').val())  || 9;
        var curMin   = parseInt($('#nb-min').val())   || 0;
        var curAmpm  = $('#nb-ampm').val() || 'AM';
        var use24    = ($('#nb-time-24').length && $('#nb-time-24').hasClass('active'));

        var $wrap = $('#nb-time-wrap');
        var rect  = $wrap[0].getBoundingClientRect();

        var $pop = $('<div id="nb-timepicker-popup"></div>').css({
            position:   'fixed',
            top:        rect.bottom + 4,
            right:      (window.innerWidth - rect.right),
            width:      200,
            background: '#1a1d21',
            border:     '1px solid #3a3f44',
            borderRadius: '4px',
            boxShadow:  '0 4px 16px rgba(0,0,0,0.5)',
            padding:    '10px',
            boxSizing:  'border-box',
            zIndex:     1000030
        });
        $pop.on('click', function(e) { e.stopPropagation(); });

        if (!use24) {
            var $modeRow = $('<div></div>').css({ display:'flex', gap:'4px', marginBottom:'8px' });
            var $amBtn = $('<button type="button">AM</button>').css(nbTimeBtn(curAmpm === 'AM'));
            var $pmBtn = $('<button type="button">PM</button>').css(nbTimeBtn(curAmpm === 'PM'));
            var $t24   = $('<button type="button" id="nb-time-24">24h</button>').css(nbTimeBtn(false));
            $amBtn.on('click', function() { curAmpm = 'AM'; $amBtn.css(nbTimeBtn(true)); $pmBtn.css(nbTimeBtn(false)); $('#nb-ampm').val('AM'); });
            $pmBtn.on('click', function() { curAmpm = 'PM'; $pmBtn.css(nbTimeBtn(true)); $amBtn.css(nbTimeBtn(false)); $('#nb-ampm').val('PM'); });
            $t24.on('click', function() {
                use24 = true;
                if (curHour === 12 && curAmpm === 'AM') curHour = 0;
                else if (curAmpm === 'PM' && curHour !== 12) curHour += 12;
                nbCloseTimePicker();
                $('#nb-hour').val(curHour); $('#nb-min').val(curMin); $('#nb-ampm').val('24');
                var $p = nbBuild24Popup(curHour, curMin, rect);
                $('body').append($p);
                _nbTimeOpen = true;
            });
            $modeRow.append($amBtn).append($pmBtn).append($('<span></span>').css({ flex:1 })).append($t24);
            $pop.append($modeRow);
        }

        $pop.append($('<div>Hour</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var cols = use24 ? 6 : 4;
        var hours = use24 ? 24 : 12;
        var startH = use24 ? 0 : 1;
        var $hGrid = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(' + cols + ',1fr)', gap:'3px', marginBottom:'8px' });

        for (var h = startH; h < startH + hours; h++) {
            (function(hVal) {
                var is24Val = use24 ? hVal : (curAmpm === 'AM' ? (hVal === 12 ? 0 : hVal) : (hVal === 12 ? 12 : hVal + 12));
                var isSel   = (curHour === (use24 ? hVal : is24Val));
                var $h = $('<button type="button">' + (use24 ? (hVal < 10 ? '0'+hVal : hVal) : hVal) + '</button>').css(nbTimeGridBtn(isSel));
                if (isSel) $h.addClass('nb-t-sel');
                $h.on('click', function() {
                    $hGrid.find('.nb-t-sel').css(nbTimeGridBtn(false)).removeClass('nb-t-sel');
                    $(this).css(nbTimeGridBtn(true)).addClass('nb-t-sel');
                    curHour = use24 ? hVal : is24Val;
                    $('#nb-hour').val(use24 ? hVal : is24Val);
                    nbSyncTimeDisplay();
                });
                $hGrid.append($h);
            })(h);
        }
        $pop.append($hGrid);

        $pop.append($('<div>Minute</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $mRow = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'3px' });
        [0, 15, 30, 45].forEach(function(m) {
            var mm   = (m < 10 ? '0' : '') + m;
            var isSel = (curMin === m);
            var $m = $('<button type="button">:' + mm + '</button>').css(nbTimeGridBtn(isSel));
            if (isSel) $m.addClass('nb-t-msel');
            $m.on('click', function() {
                $mRow.find('.nb-t-msel').css(nbTimeGridBtn(false)).removeClass('nb-t-msel');
                $(this).css(nbTimeGridBtn(true)).addClass('nb-t-msel');
                curMin = m;
                $('#nb-min').val(mm);
                nbSyncTimeDisplay();
                if ($('#nb-hour').val() !== '') nbCloseTimePicker();
            });
            $mRow.append($m);
        });
        $pop.append($mRow);
        $('body').append($pop);

        var popH = $pop.outerHeight();
        if (rect.bottom + popH + 4 > window.innerHeight - 8) $pop.css('top', rect.top - popH - 4);
    }

    function nbBuild24Popup(curHour, curMin, rect) {
        var $pop = $('<div id="nb-timepicker-popup"></div>').css({
            position:'fixed', top: rect.bottom+4, right: (window.innerWidth - rect.right),
            width: 200,
            background:'#1a1d21', border:'1px solid #3a3f44', borderRadius:'4px',
            boxShadow:'0 4px 16px rgba(0,0,0,0.5)', padding:'10px', boxSizing:'border-box', zIndex:1000030
        });
        $pop.on('click', function(e) { e.stopPropagation(); });
        var $switchRow = $('<div></div>').css({ display:'flex', justifyContent:'flex-end', marginBottom:'8px' });
        var $t12 = $('<button type="button">12h</button>').css(nbTimeBtn(false));
        $t12.on('click', function() {
            $('#nb-ampm').val('AM'); $('#nb-hour').val(''); $('#nb-min').val(curMin);
            nbCloseTimePicker();
            nbOpenTimePicker();
        });
        $switchRow.append($t12);
        $pop.append($switchRow);
        $pop.append($('<div>Hour</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $hGrid = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(6,1fr)', gap:'3px', marginBottom:'8px' });
        for (var h = 0; h < 24; h++) {
            (function(hh) {
                var isSel = (curHour === hh);
                var $b = $('<button type="button">' + (hh < 10 ? '0'+hh : hh) + '</button>').css(nbTimeGridBtn(isSel));
                if (isSel) $b.addClass('nb-t-sel');
                $b.on('click', function() {
                    $hGrid.find('.nb-t-sel').css(nbTimeGridBtn(false)).removeClass('nb-t-sel');
                    $(this).css(nbTimeGridBtn(true)).addClass('nb-t-sel');
                    curHour = hh; $('#nb-hour').val(hh); nbSyncTimeDisplay();
                });
                $hGrid.append($b);
            })(h);
        }
        $pop.append($hGrid);
        $pop.append($('<div>Minute</div>').css({ fontSize:'10px', color:'#555', marginBottom:'4px' }));
        var $mRow = $('<div></div>').css({ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'3px' });
        [0,15,30,45].forEach(function(m) {
            var mm = (m<10?'0':'')+m;
            var isSel = (curMin === m);
            var $b = $('<button type="button">:'+mm+'</button>').css(nbTimeGridBtn(isSel));
            if (isSel) $b.addClass('nb-t-msel');
            $b.on('click', function() {
                $mRow.find('.nb-t-msel').css(nbTimeGridBtn(false)).removeClass('nb-t-msel');
                $(this).css(nbTimeGridBtn(true)).addClass('nb-t-msel');
                curMin = m; $('#nb-min').val(mm); nbSyncTimeDisplay();
                if ($('#nb-hour').val() !== '') nbCloseTimePicker();
            });
            $mRow.append($b);
        });
        $pop.append($mRow);
        var popH = $pop.outerHeight();
        if (rect.bottom + popH + 4 > window.innerHeight - 8) $pop.css('top', rect.top - popH - 4);
        return $pop;
    }

    function nbTimeBtn(active) {
        return { background: active ? '#3a3f44' : 'none', border: '1px solid ' + (active ? '#555' : '#3a3f44'),
                 borderRadius: '3px', color: active ? '#e0e0e0' : '#555', fontSize: '10px',
                 padding: '2px 7px', cursor: 'pointer', fontWeight: active ? '600' : '400' };
    }
    function nbTimeGridBtn(active) {
        return { background: active ? '#3a3f44' : '#2a2e33', border: '1px solid ' + (active ? '#555' : '#2a2e33'),
                 borderRadius: '3px', color: active ? '#fff' : '#888', fontSize: '10px',
                 padding: '3px 2px', cursor: 'pointer', textAlign: 'center', lineHeight: '1.4' };
    }
    function nbSyncTimeDisplay() {
        var h   = parseInt($('#nb-hour').val());
        var m   = $('#nb-min').val() || '00';
        var ap  = $('#nb-ampm').val();
        if (isNaN(h)) { $('#nb-time-display').text('Select time').css('color','#999'); return; }
        var disp;
        if (ap === '24') {
            disp = (h < 10 ? '0'+h : h) + ':' + m;
        } else {
            var h12 = h % 12 || 12;
            disp = h12 + ':' + m + ' ' + ((ap === 'PM' || h >= 12) ? 'PM' : 'AM');
        }
        $('#nb-time-display').text(disp).css('color','#e0e0e0');
    }

    $(document).on('click', '#nb-time-display', function(e) {
        e.stopPropagation();
        if (_nbTimeOpen) { nbCloseTimePicker(); } else { nbOpenTimePicker(); }
    });
    $(document).on('click.nbtimecal', function(e) {
        if (_nbTimeOpen && !$(e.target).closest('#nb-timepicker-popup, #nb-time-display').length) {
            nbCloseTimePicker();
        }
    });

    $(document).on('click', '#nb-submit', function() {
        var service  = $('#nb-service').val();
        var name     = $('#nb-name').val().trim();
        var email    = $('#nb-email').val().trim();
        var date     = $('#nb-date').val();
        var _h = parseInt($('#nb-hour').val());
        var _m = $('#nb-min').val() || '00';
        if (isNaN(_h)) { _h = 9; }
        var time = (_h < 10 ? '0'+_h : _h) + ':' + _m;
        if (!service || !name || !email || !date) {
            showToast('Please fill in required fields', 'error');
            return;
        }
        var $btn = $(this).prop('disabled', true).text('Creating...');
        $.post(window.Impulse.products.ajaxurl, {
            action: 'instinctor_create_booking',
            nonce:  window.Impulse.adminNonce,
            product_id:     service,
            customer_name:  name,
            customer_email: email,
            customer_phone: $('#nb-phone').val(),
            booking_date:   date,
            booking_time:   time,
            note:           $('#nb-note').val()
        }, function(res) {
            $btn.prop('disabled', false).text('Create Booking');
            if (res.success) {
                showToast('Booking created');
                closeNewBookingPanel();
                loadBookingsList();
                loadAllBookingDates();
                loadBookingsStats();
            } else {
                showToast(res.data ? res.data.message : 'Error creating booking', 'error');
            }
        });
    });

    
    function loadProductAddonsCard(containerId) {
        $('#' + containerId).html('<div style="font-size:11px;color:#555;text-align:center;padding:16px 8px;line-height:1.6">Add-Ons are now configured in each Products block in Impulse.</div>');
    }

    function loadVolumeDiscountsCard(containerId) {
        var $c = $('#' + containerId);
        $.post(ajaxurl, { action: 'instinctor_get_volume_tiers', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) { $c.html('<div style="color:#555;font-size:11px">Failed to load</div>'); return; }
            var tiers = res.data.tiers;
            window._volumeData = tiers;
            var html = crudCardList(tiers, function(t) {
                var disc = t.discount_type === 'percent' ? t.discount_value + '% off' : '$' + parseFloat(t.discount_value).toFixed(2) + ' off';
                var qty = 'Buy ' + t.min_quantity + (t.max_quantity ? '–' + t.max_quantity : '+');
                return crudCardRow('volume_discounts', t.id, qty, disc);
            });
            $c.html(html);
            $('#card-stats-volume_discounts').html(cardStat(tiers.length, 'Tiers'));
        }).fail(function(xhr) {
            $c.html('<div style="color:#555;font-size:11px;padding:8px">Error: ' + (xhr.status || 'unknown') + ' — check PHP error log</div>');
        });
    }

    function loadCouponsCard(containerId) {
        var $c = $('#' + containerId);
        $.post(ajaxurl, { action: 'instinctor_get_all_coupons', _wpnonce: couponNonce() }, function(res) {
            if (!res.success) { $c.html('<div style="color:#555;font-size:11px">Failed to load</div>'); return; }
            var coupons = res.data.coupons || [];
            window._couponData = coupons;
            var currency = (window.Impulse.products && window.Impulse.products.currency) || '$';
            var active = coupons.filter(function(c){ return c.status === 'active'; }).length;
            var html = crudCardList(coupons, function(c) {
                var disc = c.discount_type === 'percent' ? c.amount + '% off' : currency + parseFloat(c.amount).toFixed(2) + ' off';
                return crudCardRow('coupons', c.id, escapeHtml(c.code), disc);
            });
            $c.html(html);
            $('#card-stats-coupons').html(cardStat(coupons.length, 'Total') + cardStat(active, 'Active'));
        });
    }

    function loadLoyaltyCard(containerId) {
        var $c = $('#' + containerId);
        $.post(ajaxurl, { action: 'instinctor_get_loyalty_stats', nonce: window.Impulse.adminNonce }, function(res) {
            if (res.success) {
                var d = res.data;
                $('#card-stats-loyalty').html(cardStat(d.members, 'Members') + cardStat(d.active_points.toLocaleString(), 'Points'));
            }
        });
        $.post(ajaxurl, { action: 'instinctor_get_loyalty_settings', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) { $c.html('<div style="font-size:11px;color:#555;padding:8px">Failed to load</div>'); return; }
            var s = res.data.settings;
            function inp(id, val) {
                return '<input id="' + id + '" type="number" value="' + (val || 0) + '" style="width:72px;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box;text-align:right">';
            }
            function row(label, ctrl) {
                return '<div class="impulse-inline-right" style="margin-bottom:6px">'
                    + '<span style="font-size:11px;color:#999">' + label + '</span>'
                    + ctrl + '</div>';
            }
            var html = '';
            html += row('Points per $1 spent',  inp('lc-ppd',  s.points_per_dollar));
            html += row('Point value ($)',       inp('lc-pv',   s.points_value));
            html += row('Min to redeem',         inp('lc-minr', s.min_redeem));
            html += row('Signup bonus',          inp('lc-sp',   s.signup_points));
            html += row('Referral bonus',        inp('lc-ref',  s.referral_points));
            html += row('Expire (days)',         inp('lc-exp',  s.expiry_days));
            html += '<div style="margin-top:8px"><button type="button" id="lc-save-btn" class="impulse-btn-sm" style="height:26px;padding:0 10px">Save</button></div>';
            $c.html(html);
        });
    }

    $(document).on('click', '#lc-save-btn', function() {
        var $btn = $(this).prop('disabled', true).text('Saving…');
        $.post(ajaxurl, {
            action: 'instinctor_save_loyalty_settings',
            nonce: window.Impulse.adminNonce,
            enabled: 1,
            points_per_dollar: $('#lc-ppd').val(),
            points_value:      $('#lc-pv').val(),
            min_redeem:        $('#lc-minr').val(),
            signup_points:     $('#lc-sp').val(),
            referral_points:   $('#lc-ref').val(),
            expiry_days:       $('#lc-exp').val()
        }, function(res) {
            $btn.prop('disabled', false).text('Save Settings');
            if (res.success) showImpulseToast('Loyalty settings saved');
            else showImpulseToast(res.data.message || 'Save failed', 'error');
        });
    });

    function openGiftCardForm(card, targetId) {
        var c = card || { id: 0, code: '', initial_balance: '', current_balance: '', expiry_date: '', status: 'active', email: '', note: '' };
        var isNew = !c.id;
        var $target = $('#' + (targetId || 'settings-detail-content'));
        var IS = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box';
        var cell = function(label, ctrl) {
            return '<div><div style="font-size:11px;color:#888;margin-bottom:3px">' + label + '</div>' + ctrl + '</div>';
        };
        function numInp(id, val, placeholder) {
            return '<input id="' + id + '" type="text" inputmode="numeric" value="' + escapeHtml(String(val !== undefined && val !== null ? val : '')) + '"'
                + ' placeholder="' + escapeHtml(placeholder || '') + '" style="' + IS + '">';
        }

        var isActive = c.status !== 'inactive';
        var html = '<div style="display:flex;margin-bottom:10px">';
        html += '<button type="button" class="impulse-btn-sm gc-status-btn' + (isActive ? ' active' : '') + '" data-status="active" style="border-radius:3px 0 0 3px;flex:1">Active</button>';
        html += '<button type="button" class="impulse-btn-sm gc-status-btn' + (!isActive ? ' active' : '') + '" data-status="inactive" style="border-radius:0 3px 3px 0;flex:1">Inactive</button>';
        html += '</div>';

        html += '<input type="hidden" id="gc-id" value="' + (c.id || '') + '">';

        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Code</div>';
        html += '<div style="display:flex;gap:6px">';
        html += '<input id="gc-code" type="text" value="' + escapeHtml(c.code || '') + '" placeholder="e.g. GIFT-XXXX"'
            + ' style="flex:1;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;font-family:monospace;padding:0 8px;box-sizing:border-box;text-transform:uppercase">';
        html += '<button type="button" id="gc-gen-code" class="impulse-btn-sm">Generate</button>';
        html += '</div></div>';

        html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 10px;margin-bottom:8px">';
        if (isNew) {
            html += cell('Initial Balance', numInp('gc-initial', c.initial_balance || '', '0.00'));
            html += cell('Expiry Date',     formDateBtn('gc-expiry', c.expiry_date || '', 'Never'));
        } else {
            html += cell('Initial Balance', numInp('gc-initial', c.initial_balance || '', '0.00'));
            html += cell('Current Balance', numInp('gc-current', c.current_balance || '', '0.00'));
            html += cell('Expiry Date',     formDateBtn('gc-expiry', c.expiry_date || '', 'Never'));
            html += '<div></div>';
        }
        html += '</div>';

        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Recipient Email <span style="color:#555">(optional)</span></div>';
        html += '<input id="gc-email" type="email" value="' + escapeHtml(c.email || '') + '" placeholder="customer@example.com" style="' + IS + '"></div>';

        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Note <span style="color:#555">(internal)</span></div>';
        html += '<input id="gc-note" type="text" value="' + escapeHtml(c.note || '') + '" placeholder="Optional…" style="' + IS + '"></div>';

        if (!isNew) {
            html += '<button type="button" class="impulse-btn-sm" id="gc-delete-btn" style="color:#555">Delete Gift Card</button>';
        }

        $target.html(html);

        $target.on('click', '#gc-gen-code', function() {
            var code = 'GIFT-' + Math.random().toString(36).substr(2,4).toUpperCase() + '-' + Math.random().toString(36).substr(2,4).toUpperCase();
            $('#gc-code').val(code);
            scheduleGcSave();
        });

        $target.on('click', '.gc-status-btn', function() {
            $('.gc-status-btn').removeClass('active'); $(this).addClass('active');
            scheduleGcSave();
        });

        var _gcTimer = null;
        function scheduleGcSave() { clearTimeout(_gcTimer); _gcTimer = setTimeout(saveGiftCard, 800); }
        function saveGiftCard() {
            var code = $('#gc-code').val().trim();
            if (!code) return;
            $.post(ajaxurl, {
                action: 'instinctor_save_gift_card',
                nonce: window.Impulse.adminNonce,
                id: $('#gc-id').val(),
                code: code,
                initial_balance: $('#gc-initial').val(),
                current_balance: $('#gc-current').val() || $('#gc-initial').val(),
                expiry_date: $('#gc-expiry').val(),
                email: $('#gc-email').val(),
                note: $('#gc-note').val(),
                status: $('.gc-status-btn.active').data('status') || 'active'
            }, function(res) {
                if (res.success) {
                    if (!$('#gc-id').val() && res.data && res.data.id) {
                        $('#gc-id').val(res.data.id);
                    }
                    showImpulseToast('Gift card saved');
                    if (ordersTabMode === 'clients') loadClientsCenter();
                    else {
                        var $cardBody = $('#card-body-gift_cards');
                        if ($cardBody.length) { $cardBody.data('loaded', false); loadGiftCardsCard('card-body-gift_cards'); }
                    }
                } else {
                    showImpulseToast((res.data && res.data.message) || 'Error saving gift card', 'error');
                }
            });
        }
        
        $target.off('input.gc change.gc')
               .on('input.gc', '#gc-code,#gc-initial,#gc-current,#gc-email,#gc-note', scheduleGcSave)
               .on('change.gc', '#gc-expiry', scheduleGcSave);

        $target.on('click', '#gc-delete-btn', function() {
            if (!window.impulseConfirm('Delete this gift card?')) return;
            $.post(ajaxurl, { action: 'instinctor_delete_gift_card', nonce: window.Impulse.adminNonce, id: $('#gc-id').val() }, function(res) {
                if (res.success) {
                    showImpulseToast('Gift card deleted');
                    $target.html('');
                    if (ordersTabMode === 'clients') loadClientsCenter();
                    else {
                        var $cardBody = $('#card-body-gift_cards');
                        if ($cardBody.length) { $cardBody.data('loaded', false); loadGiftCardsCard('card-body-gift_cards'); }
                    }
                } else showImpulseToast(res.data || 'Error', 'error');
            });
        });
    }

    function loadGiftCardsCard(containerId) {
        var $c = $('#' + containerId);
        $.post(ajaxurl, { action: 'instinctor_get_gift_cards', nonce: window.Impulse.adminNonce, status: '' }, function(res) {
            if (!res.success) { $c.html('<div style="color:#555;font-size:11px">Failed to load</div>'); return; }
            var cards = res.data.cards;
            window._giftCardData = cards;
            var active = cards.filter(function(c){ return c.status === 'active'; }).length;
            var html = crudCardList(cards, function(c) {
                var dot = '<span style="width:6px;height:6px;border-radius:50%;background:' + (c.status === 'active' ? '#e0e0e0' : '#555') + ';display:inline-block;margin-left:6px;flex-shrink:0"></span>';
                return '<div class="impulse-card-list-row" data-feature="gift_cards" data-id="' + c.id + '" style="display:flex;justify-content:space-between;align-items:center;padding:5px 0;border-bottom:1px solid #1a1d21;cursor:pointer">'
                    + '<span style="font-size:11px;color:#e0e0e0;font-family:monospace">' + escapeHtml(c.code) + '</span>'
                    + '<span style="display:flex;align-items:center"><span style="font-size:11px;color:#888">' + c.current_balance + '</span>' + dot + '</span>'
                    + '</div>';
            });
            $c.html(html);
            $('#card-stats-gift_cards').html(cardStat(cards.length, 'Total') + cardStat(active, 'Active'));
        });
    }

    

    

    
    var ordersTabMode = 'orders';
    var rmaFilterStatus = '';
    var returnsLoaded = false;
    
    Object.defineProperty(window, 'returnsMode', {
        get: function() { return ordersTabMode === 'returns'; },
        set: function(v) {  }
    });

    function setOrdersTabMode(mode) {
        if (ordersTabMode === mode) return;
        ordersTabMode = mode;

        $('#orders-mode-orders, #orders-mode-clients, #orders-mode-returns').removeClass('active');
        $('#orders-mode-' + mode).addClass('active');

        $('#dashboard-orders-list').toggle(mode === 'orders');
        $('#dashboard-returns-list').toggle(mode === 'returns');
        $('#clients-center-list').toggle(mode === 'clients');

        $('#orders-left-block').toggle(mode === 'orders');
        $('#returns-left-block').toggle(mode === 'returns');
        $('#clients-left-block').toggle(mode === 'clients');

        $('#orders-col-toggles').toggle(mode === 'orders');
        $('#orders-sort-header').toggle(mode === 'orders');
        $('#clients-toolbar-extra').toggle(mode === 'clients');

        $('#store-stats-revenue').toggle(mode !== 'clients');
        $('#store-stats-clients').toggle(mode === 'clients');

        $('#order-detail-header').hide();
        $('#clients-right-header').hide();
        $('#dashboard-detail-content').html('');
        $('#customer-detail-content').html('');
        storeRightCollapse();

        if (mode === 'returns') {
            if (!returnsLoaded) { returnsLoaded = true; loadReturnsList(); }
        } else if (mode === 'clients') {
            if (!clientsState.initialized) initClientsWorkspace();
            else loadClientsCenter();
        }
    }

    $(document).on('click', '#orders-mode-orders',  function() { setOrdersTabMode('orders'); });
    $(document).on('click', '#orders-mode-clients', function() { setOrdersTabMode('clients'); });
    $(document).on('click', '#orders-mode-returns', function() { setOrdersTabMode('returns'); });

    var productsTabMode = 'products';

    function setProductsTabMode(mode) {
        if (productsTabMode === mode) return;
        productsTabMode = mode;

        $('#products-mode-products, #products-mode-bundles').removeClass('active');
        $('#products-mode-' + mode).addClass('active');

        $('#products-tab-content').toggle(mode === 'products');
        $('#bundles-center-list').toggle(mode === 'bundles');
        $('#products-topbar-controls').toggle(mode === 'products');
        $('#bundles-toolbar-extra').toggle(mode === 'bundles');

        if (mode === 'bundles') {
            $('#products-cats-panel').hide();
        } else {
            $('#products-cats-panel').show();
        }

        if (mode === 'bundles') {
            setProductsRightTitle('Bundles');
            $('#impulse-products-edit').html('');
            loadBundlesCenter();
        } else {
            setProductsRightTitle('');
            $('#impulse-products-edit').html('');
        }
    }

    $(document).on('click', '#products-mode-products', function() { setProductsTabMode('products'); });
    $(document).on('click', '#products-mode-bundles',  function() { setProductsTabMode('bundles'); });

    $(document).on('click', '#bundles-new-btn', function() {
        openBundleForm(null, 'impulse-products-edit');
        setProductsRightTitle('New Bundle');
        $('#bundles-center-list .impulse-list-item').removeClass('active');
    });

    $(document).on('click', '#bundles-center-list .impulse-list-item[data-bundle-id]', function() {
        var id = $(this).data('bundle-id');
        var bundle = (window._bundleData || []).find(function(b) { return b.id == id; });
        $('#bundles-center-list .impulse-list-item').removeClass('active');
        $(this).addClass('active');
        $('[data-workspace="store"] .impulse-store-right-content').hide();
        $('[data-workspace="store"] .impulse-store-right-content[data-section="products"]').show();
        if (typeof window.storeRightExpand === 'function') window.storeRightExpand();
        openBundleForm(bundle || null, 'impulse-products-edit');
        setProductsRightTitle(bundle ? 'Edit Bundle' : 'New Bundle');
    });

    function loadBundlesCenter() {
        var $list = $('#bundles-center-list');
        $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Loading…</li>');
        $.post(ajaxurl, { action: 'instinctor_get_bundles', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) { $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Failed to load</li>'); return; }
            var bundles = res.data.bundles;
            window._bundleData = bundles;
            if (!bundles.length) {
                $list.html('<li class="impulse-empty"><div class="impulse-empty-title">No bundles yet</div><div class="impulse-empty-sub">Click + New Bundle to create one</div></li>');
                return;
            }
            var html = '';
            bundles.forEach(function(b) {
                var disc = b.discount_type === 'percent' ? b.discount_value + '% off' : '$' + parseFloat(b.discount_value).toFixed(2) + ' off';
                var products = Array.isArray(b.products) ? b.products : (function(){ try { return JSON.parse(b.products || '[]'); } catch(e){ return []; } })();
                var pCount = products.length + ' product' + (products.length !== 1 ? 's' : '');
                var isActive = parseInt(b.is_active);
                html += '<li class="impulse-list-item" data-bundle-id="' + b.id + '" style="display:flex;align-items:center;padding:6px 12px;border-bottom:1px solid #2a2e33;cursor:pointer;gap:8px;font-size:11px">';
                html += '<span style="width:6px;height:6px;border-radius:50%;background:' + (isActive ? '#e0e0e0' : '#555') + ';flex-shrink:0"></span>';
                html += '<span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e0e0e0;font-weight:500">' + escapeHtml(b.name) + '</span>';
                html += '<span style="color:#888;flex-shrink:0">' + escapeHtml(pCount) + '</span>';
                html += '<span style="color:#888;flex-shrink:0">' + escapeHtml(disc) + '</span>';
                html += '<button type="button" class="impulse-btn-sm btn-delete-bundle-list" data-id="' + b.id + '" style="width:22px;height:22px;padding:0;flex-shrink:0;font-size:14px;line-height:1" title="Delete">&times;</button>';
                html += '</li>';
            });
            $list.html(html);
        }).fail(function() {
            $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Failed</li>');
        });
    }

    $(document).on('change', 'input[name="rma_status_filter"]', function() {
        rmaFilterStatus = $(this).val();
        loadReturnsList();
    });

    function loadReturnsList() {
        $('#dashboard-returns-list').html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Loading...</li>');
        $.post(ajaxurl, { action: 'instinctor_get_rmas', nonce: window.Impulse.adminNonce, status: rmaFilterStatus }, function(res) {
            if (!res.success) return;
            var rmas = res.data.rmas;
            var st   = res.data.stats;

            $('#rma-count-all').text(st.total || 0);
            $('#rma-count-pending').text(st.pending || 0);
            $('#rma-count-approved').text(st.approved || 0);
            $('#rma-count-shipped').text(st.shipped || 0);
            $('#rma-count-refunded').text(st.refunded || 0);
            $('#rma-count-completed').text(st.completed || 0);

            if (!rmas.length) {
                $('#dashboard-returns-list').html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">No return requests' + (rmaFilterStatus ? ' with this status' : ' yet') + '.</li>');
                return;
            }

            var html = '';
            rmas.forEach(function(r) {
                html += '<li class="impulse-list-item impulse-return-row" data-rma-id="' + r.id + '">';
                html += '<span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e0e0e0;font-weight:500;font-size:11px">' + escapeHtml(r.customer_name || r.reason_label || r.reason) + '</span>';
                html += '<span style="color:#555;font-size:11px;flex-shrink:0">' + escapeHtml(r.order_number || '') + '</span>';
                html += '<span class="impulse-status impulse-status-' + escapeHtml(r.status) + '">' + escapeHtml(r.status_label) + '</span>';
                html += '<span style="width:60px;text-align:right;color:#555;font-size:11px;flex-shrink:0">' + escapeHtml(r.created_at ? timeAgo(r.created_at) : '') + '</span>';
                html += '</li>';
            });
            $('#dashboard-returns-list').html(html);
        });
    }

    function timeAgo(dateStr) {
        var now = new Date();
        var then = new Date(dateStr);
        var diff = Math.floor((now - then) / 1000);
        if (diff < 60)    return 'just now';
        if (diff < 3600)  return Math.floor(diff/60) + 'm ago';
        if (diff < 86400) return Math.floor(diff/3600) + 'h ago';
        if (diff < 604800) return Math.floor(diff/86400) + 'd ago';
        return Math.floor(diff/604800) + 'w ago';
    }

    $(document).on('click', '.impulse-return-row', function() {
        var id = $(this).data('rma-id');
        $('.impulse-return-row').removeClass('active');
        $(this).addClass('active');
        $('#dashboard-detail-content').html('<div style="padding:40px 16px;text-align:center;color:#555">Loading...</div>');

        $.post(ajaxurl, { action: 'instinctor_get_rma', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (!res.success) {
                $('#dashboard-detail-content').html('<div style="padding:16px;color:#999">Error loading return</div>');
                return;
            }
            renderReturnDetail(res.data.rma, res.data.currency || '$');
        });
    });

    function renderReturnDetail(r, currency) {
        if (!currency) currency = (window.Impulse && window.Impulse.store && window.Impulse.store.currency) || '$';
        if (typeof window.storeRightExpand === 'function') window.storeRightExpand();
        $('#order-detail-header').show().find('span').text(((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.returns.replace(/s$/, '') : 'Return') + ' Details');

        var html = '<div style="padding:8px 12px 16px">';

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Status</label>';
        html += '<span class="impulse-status impulse-status-' + escapeHtml(r.status) + '">' + escapeHtml(r.status_label || r.status) + '</span>';
        html += '</div>';

        if (r.customer_name || r.customer_email) {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Customer</label>';
            if (r.customer_name) html += '<div style="color:#e0e0e0;font-size:11px">' + escapeHtml(r.customer_name) + '</div>';
            if (r.customer_email) html += '<a href="mailto:' + escapeHtml(r.customer_email) + '" style="color:#888;font-size:11px;text-decoration:none">' + escapeHtml(r.customer_email) + '</a>';
            html += '</div>';
        }

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Order</label>';
        html += '<div style="font-size:11px;color:#e0e0e0;cursor:pointer;text-decoration:underline;text-decoration-color:#555" class="impulse-return-order-link" data-order-id="' + escapeHtml(r.order_id+'') + '">#' + escapeHtml(r.order_number || r.order_id+'') + '</div>';
        html += '</div>';

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Reason</label>';
        html += '<div style="font-size:11px;color:#ccc">' + escapeHtml(r.reason_label || r.reason) + '</div>';
        if (r.reason_detail) html += '<div style="font-size:11px;color:#888;margin-top:2px">' + escapeHtml(r.reason_detail) + '</div>';
        html += '</div>';

        if (r.items && r.items.length) {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Items</label>';
            r.items.forEach(function(item) {
                html += '<div style="font-size:11px;color:#ccc;margin-bottom:3px">' + escapeHtml(item.product_name) + ' × ' + item.quantity + '</div>';
            });
            html += '</div>';
        }

        if (r.status === 'pending') {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:6px">Action</label>';
            html += '<div style="display:flex;gap:4px;align-items:center;margin-bottom:8px">';
            html += '<span style="font-size:11px;color:#aaa">Refund</span>';
            html += '<input type="number" id="rma-refund-amount" value="' + (r.refund_amount || 0) + '" style="width:72px">';
            html += '</div>';
            html += '<div style="display:flex;gap:4px">';
            html += '<button type="button" class="impulse-btn-sm rma-approve-btn" data-id="' + r.id + '">Approve</button>';
            html += '<button type="button" class="impulse-btn-sm rma-reject-btn" data-id="' + r.id + '" style="color:#555">Reject</button>';
            html += '</div>';
            html += '</div>';
        }

        if (r.status === 'approved' && r.refund_amount > 0) {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:6px">Action</label>';
            html += '<div style="font-size:11px;color:#888;margin-bottom:6px">Refund ' + currency + parseFloat(r.refund_amount).toFixed(2) + ' immediately</div>';
            html += '<button type="button" class="impulse-btn-sm rma-refund-now-btn" data-id="' + r.id + '">Refund Now</button>';
            html += '</div>';
        }

        if (r.admin_notes) {
            html += '<div class="impulse-detail-section">';
            html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Notes</label>';
            html += '<div style="font-size:11px;color:#888;font-style:italic">' + escapeHtml(r.admin_notes) + '</div>';
            html += '</div>';
        }

        html += '</div>';
        $('#dashboard-detail-content').html(html);
    }

    $(document).on('click', '.impulse-return-order-link', function() {
        var orderId = $(this).data('order-id');
        if (!orderId) return;
        
        $('#orders-mode-orders').trigger('click');
        loadOrderDetail(orderId);
    });

    $(document).on('click', '.rma-approve-btn', function() {
        var id     = $(this).data('id');
        var amount = $('#rma-refund-amount').val();
        var $btn   = $(this).prop('disabled', true);
        $.post(ajaxurl, { action: 'instinctor_approve_rma', nonce: window.Impulse.adminNonce, id: id, refund_amount: amount }, function(res) {
            $btn.prop('disabled', false);
            if (res.success) {
                showToast('Return approved');
                loadReturnsList();
                renderReturnDetail(res.data.rma, res.data.currency);
            } else showToast('Failed to approve', 'error');
        });
    });

    $(document).on('click', '.rma-reject-btn', function() {
        var id   = $(this).data('id');
        var $btn = $(this).prop('disabled', true);
        $.post(ajaxurl, { action: 'instinctor_reject_rma', nonce: window.Impulse.adminNonce, id: id, reason: 'Rejected by admin' }, function(res) {
            $btn.prop('disabled', false);
            if (res.success) {
                showToast('Return rejected');
                loadReturnsList();
                $.post(ajaxurl, { action: 'instinctor_get_rma', nonce: window.Impulse.adminNonce, id: id }, function(r) {
                    if (r.success) renderReturnDetail(r.data.rma, r.data.currency);
                });
            } else showToast('Failed to reject', 'error');
        });
    });

    $(document).on('click', '.rma-refund-now-btn', function() {
        var id   = $(this).data('id');
        var $btn = $(this).prop('disabled', true).text('Processing...');
        $.post(ajaxurl, { action: 'instinctor_rma_refund_now', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            $btn.prop('disabled', false).text('Refund Now');
            if (res.success) {
                showToast('Refund processed');
                loadReturnsList();
                renderReturnDetail(res.data.rma, res.data.currency);
            } else {
                showToast(res.data || 'Refund failed', 'error');
            }
        }).fail(function() {
            $btn.prop('disabled', false).text('Refund Now');
            showToast('Request failed', 'error');
        });
    });

    

    var shippingAfterShipLoaded = false;

    function loadShippingAfterShip() {
        var $target = $('#shipping-aftership-form');
        $.post(ajaxurl, { action: 'instinctor_get_tracking_settings', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) return;
            var s = res.data.settings;

            var inp = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;color:#e0e0e0;padding:0 8px;font-size:11px;border-radius:3px;box-sizing:border-box';
            var lbl = function(t) { return '<div style="font-size:11px;color:#999;margin-bottom:4px">' + t + '</div>'; };

            var html = '';

            html += '<label style="display:flex;align-items:center;gap:8px;font-size:11px;color:#999;cursor:pointer;margin-bottom:12px">';
            html += '<input type="checkbox" id="ot-aftership-enabled"' + (s.aftership_enabled ? ' checked' : '') + '> Enable automatic carrier tracking via AfterShip';
            html += '</label>';

            html += '<div id="ot-aftership-body"' + (!s.aftership_enabled ? ' style="display:none"' : '') + '>';

            html += '<div style="margin-bottom:12px">' + lbl('API Key');

             html += '<form autocomplete="off" onsubmit="return false" style="display:contents">';
            html += '<input id="ot-aftership-api-key" type="password" autocomplete="new-password" value="' + escapeHtml(s.aftership_api_key) + '" placeholder="Paste key from aftership.com…" style="' + inp + '">';
            html += '</form>';
            html += '</div>';

            html += '<div style="margin-bottom:12px">' + lbl('Sync frequency');
            html += '<div style="display:flex;gap:4px">';
            html += '<button type="button" class="impulse-btn-sm ot-freq-btn' + (s.aftership_frequency === 'hourly'     ? ' active' : '') + '" data-freq="hourly">Hourly</button>';
            html += '<button type="button" class="impulse-btn-sm ot-freq-btn' + (s.aftership_frequency === 'twicedaily' ? ' active' : '') + '" data-freq="twicedaily">Twice daily</button>';
            html += '<button type="button" class="impulse-btn-sm ot-freq-btn' + (s.aftership_frequency === 'daily'      ? ' active' : '') + '" data-freq="daily">Daily</button>';
            html += '</div><input type="hidden" id="ot-aftership-frequency" value="' + escapeHtml(s.aftership_frequency || 'hourly') + '">';
            html += '</div>';

            html += '<div style="display:flex;gap:4px;margin-bottom:10px">';
            html += '<button type="button" id="ot-test-btn" class="impulse-btn-sm">Test Connection</button>';
            html += '</div>';

            html += '<div class="impulse-section-divider">Customer Tracking</div>';
            html += '<div style="margin-bottom:8px">' + lbl('Tracking page URL');
            html += '<input id="ot-tracking-page" type="text" value="' + escapeHtml(s.tracking_page || '') + '" placeholder="/track-order" style="' + inp + '">';
            html += '<div style="font-size:10px;color:#555;margin-top:4px">Page with the <strong style="color:#888">Order Tracking</strong> Impulse block. Customers look up their order by number + email.</div>';
            html += '</div>';

            html += '<div style="font-size:10px;color:#555;line-height:1.5">AfterShip supports 1,100+ carriers and auto-detects carrier from the tracking number. Tracking numbers are added per-order in the Orders list. <a href="https://www.aftership.com" target="_blank" style="color:#888">Get API key →</a></div>';

            html += '</div>'; 
            $target.html(html);
            if (typeof window.upgradeCheckboxes === 'function') window.upgradeCheckboxes($target[0]);
        });
    }

    function _saveAfterShipSettings() {
        $.post(ajaxurl, {
            action:              'instinctor_save_aftership_settings',
            nonce:               window.Impulse.adminNonce,
            aftership_enabled:   $('#ot-aftership-enabled').is(':checked') ? 1 : 0,
            aftership_api_key:   $('#ot-aftership-api-key').val() || '',
            aftership_frequency: $('#ot-aftership-frequency').val() || 'hourly',
            tracking_page:       $('#ot-tracking-page').val() || ''
        });
    }

    $(document).on('click', '.ot-freq-btn', function() {
        $('.ot-freq-btn').removeClass('active');
        $(this).addClass('active');
        $('#ot-aftership-frequency').val($(this).data('freq'));
        _saveAfterShipSettings();
    });

    $(document).on('change', '#ot-aftership-enabled', function() {
        $('#ot-aftership-body').toggle($(this).is(':checked'));
        _saveAfterShipSettings();
    });

    var _otSaveTimer;
    $(document).on('input', '#ot-aftership-api-key, #ot-tracking-page', function() {
        clearTimeout(_otSaveTimer);
        _otSaveTimer = setTimeout(_saveAfterShipSettings, 800);
    });

    $(document).on('click', '#ot-test-btn', function() {
        var $btn = $(this).prop('disabled', true).text('Testing...');
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_test_aftership',
            nonce:  window.Impulse.adminNonce,
            api_key: $('#ot-aftership-api-key').val()
        }, function(res) {
            $btn.prop('disabled', false).text('Test Connection');
            if (res.success) showToast('Connected — ' + (res.data.carriers_count || '?') + ' carriers available');
            else showToast(res.data?.message || 'Connection failed', 'error');
        });
    });

    

    

    function collectPanelFields(panel) {
        var data = {};
        $('[data-workspace="store"] .impulse-autosave[data-panel="' + panel + '"]').each(function() {
            var name = $(this).attr('name');
            if (!name) return;
            data[name] = $(this).attr('type') === 'checkbox' ? ($(this).is(':checked') ? '1' : '0') : $(this).val();
        });
        return data;
    }

    function collectSettingsForm(selector) {
        var data = {};
        $(selector).find('input, select, textarea').each(function() {
            var name = $(this).attr('name');
            if (!name) return;
            if ($(this).attr('type') === 'checkbox') {
                data[name] = $(this).is(':checked') ? '1' : '0';
            } else {
                data[name] = $(this).val();
            }
        });
        return data;
    }

    function collectGeneralSettings() {
        
        var data = {};
        $('[data-workspace="store"] .impulse-store-left-content[data-section="settings"] .impulse-autosave').each(function() {
            var name = $(this).attr('name');
            if (!name) return;
            if ($(this).attr('type') === 'checkbox') {
                data[name] = $(this).is(':checked') ? '1' : '0';
            } else {
                data[name] = $(this).val();
            }
        });
        return data;
    }

        $(document).on('change', 'select[name="store_type"]', function() {
            var $sel = $(this);
            $sel.blur(); 
            var st = $sel.val();
            window.Impulse.storeType = st;
            setTimeout(function() {

            
            var _cfgMap = {};
            try { _cfgMap = JSON.parse($('#impulse-store-nav').attr('data-store-ui-config') || '{}'); } catch (e) {}
            var _cfg = _cfgMap[st];
            if (_cfg) {
                $('.impulse-store-nav-btn[data-store-section="orders"]').first().text(_cfg.labels.orders);
                $('#store-nav-products-btn').text(_cfg.labels.products);
                $('#store-nav-bookings-btn').text(_cfg.labels.bookings);
                $('#store-nav-schedule-btn').text(_cfg.labels.schedule);
                $('#store-nav-staff-btn').text(_cfg.labels.staff);
                $('[data-store-section="products"]').toggle(!!_cfg.show.products);
                $('[data-store-section="bookings"]').toggle(!!_cfg.show.bookings);
                $('[data-store-section="schedule"]').toggle(!!_cfg.show.schedule);
                $('[data-store-section="staff"]').toggle(!!_cfg.show.staff);
                
                if (!_cfg.show.products && currentSection === 'products') switchStoreSection(_cfg.show.bookings ? 'bookings' : 'orders');
                if (!_cfg.show.bookings && currentSection === 'bookings') switchStoreSection(_cfg.show.products ? 'products' : 'orders');
                if (!_cfg.show.schedule && currentSection === 'schedule') switchStoreSection('orders');
            }

            var sections = ['orders','products','customers'];
            sections.forEach(function(s) {
                if ($('.impulse-store-section[data-section="' + s + '"]').is(':visible')) {
                    renderFeatureCards(s);
                }
            });

            
            var _ps = window._productsState;
            if (_ps && _ps.selectedProduct) {
                var openProd = (_ps.products || []).find(function(p) { return p.id === _ps.selectedProduct; });
                if (openProd && typeof window.renderProductEdit === 'function') window.renderProductEdit(openProd);
            } else {
                
                if (typeof window.setProductsRightTitle === 'function') window.setProductsRightTitle('');
                $('#impulse-products-edit').html('');
            }
            }, 50);
        });

        
        ['orders', 'customers', 'products'].forEach(function(sec) {
            var gridId = sec + '-section-grid';
            var el = document.getElementById(gridId);
            if (typeof Sortable !== 'undefined' && el) {
                new Sortable(el, {
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    handle: '.impulse-feature-card-drag',
                    filter: '#' + sec + '-feature-grid',
                    preventOnFilter: false,
                    onEnd: function() {
                        var keys = [];
                        $('#' + gridId + ' > .impulse-feature-card[data-feature]').each(function() {
                            keys.push($(this).data('feature'));
                        });
                        try { localStorage.setItem('impulse_feat_order_' + sec + '_top', JSON.stringify(keys)); } catch(e) {}
                    }
                });
            }
        });
    var _autosaveTimers = {};
    $(document).on('input change', '.impulse-autosave', function() {
        var panel = $(this).data('panel') || 'general';
        clearTimeout(_autosaveTimers[panel]);
        _autosaveTimers[panel] = setTimeout(function() {
            var $panelDiv = $('.impulse-settings-panel[data-settings="' + panel + '"]');
            var data = (panel === 'general') ? collectGeneralSettings()
                     : ($panelDiv.length ? collectSettingsForm('.impulse-settings-panel[data-settings="' + panel + '"]')
                     : collectPanelFields(panel));
            data.action = 'instinctor_save_settings';
            data.nonce = window.Impulse.adminNonce;
            $.post(ajaxurl, data, function(res) {
                if (res.success) {
                    showImpulseToast('Settings saved');
                } else {
                    showImpulseToast(res.data || 'Error saving', 'error');
                }
            });
        }, 800);
    });

    

    function loadCurrencies() {
        $.ajax({
            url: window.Impulse.api + 'currencies',
            method: 'GET',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function(res) {
            renderCurrencyList(res.currencies, res.default);
            window._currencyAvailable = res.available;
            window._currencyDefault   = res.default;
        }).fail(function() { showImpulseToast('Failed to load currencies', 'error'); });
    }

    function renderCurrencyList(currencies, defaultCode) {
        var addRow = '<div style="margin-bottom:6px;">'
            + '<button type="button" id="currency-add-btn" class="impulse-btn-sm" style="height:26px;padding:0 10px">Add Currency</button>'
            + '</div>';
        if (!currencies || currencies.length === 0) {
            $('#currency-list-wrap').html(addRow + '');
            return;
        }
        var html = addRow;
        $.each(currencies, function(_, c) {
            var isDefault = (c.code === defaultCode) || parseInt(c.is_default) === 1;
            var enabled   = parseInt(c.enabled) === 1;
            html += '<div style="background:#2a2e33;border-radius:3px;padding:8px 10px;margin-bottom:6px;display:flex;align-items:center;justify-content:space-between' + (!enabled ? ';opacity:0.5' : '') + '">';
            html += '<div style="display:flex;align-items:center;gap:8px;min-width:0;flex:1">';
            html += '<span style="font-size:12px;font-weight:600;color:#e0e0e0;flex-shrink:0">' + escapeHtml(c.symbol) + '</span>';
            html += '<span style="font-size:11px;color:#e0e0e0">' + escapeHtml(c.code) + '</span>';
            html += '<span style="font-size:11px;color:#888">' + escapeHtml(c.name) + '</span>';
            if (isDefault) {
                html += '<span style="font-size:10px;color:#555;background:#1a1d21;padding:1px 6px;border-radius:2px;flex-shrink:0">Default</span>';
            } else {
                html += '<span style="font-size:11px;color:#555;flex-shrink:0">1 ' + escapeHtml(defaultCode) + ' = ' + parseFloat(c.exchange_rate).toFixed(4) + ' ' + escapeHtml(c.code) + '</span>';
            }
            if (!enabled) html += '<span style="font-size:10px;color:#555;background:#1a1d21;padding:1px 6px;border-radius:2px;flex-shrink:0">Disabled</span>';
            html += '</div>';
            html += '<div style="display:flex;gap:4px;flex-shrink:0">';
            if (!isDefault) html += '<button type="button" class="currency-set-default impulse-btn-sm" data-id="' + c.id + '" style="height:26px;padding:0 8px;font-size:11px;color:#999">Default</button>';
            html += '<button type="button" class="currency-edit impulse-btn-sm" data-id="' + c.id + '" style="height:26px;padding:0 8px;font-size:11px">Edit</button>';
            if (!isDefault) html += '<button type="button" class="currency-delete impulse-btn-sm" data-id="' + c.id + '" style="height:26px;width:26px;padding:0;font-size:13px;color:#555">✕</button>';
            html += '</div></div>';
        });
        $('#currency-list-wrap').html(html);
        window._currencyList = currencies;
    }

    function openCurrencyForm(currency) {
        var c         = currency || {};
        var available = window._currencyAvailable || [];
        var isEdit    = !!c.id;

        var html = '<div id="cur-form" style="background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;padding:10px 12px;margin-bottom:8px">';
        html += '<input type="hidden" id="cur-id" value="' + (c.id || '') + '">';

        if (!isEdit) {
            var firstCode = available[0] || '';
            html += '<div style="margin-bottom:6px"><div style="font-size:11px;color:#888;margin-bottom:3px">Code</div>';
            html += '<div style="position:relative;width:90px" id="cur-code-wrap">';
            html += '<input type="hidden" id="cur-code" value="' + escapeHtml(firstCode) + '">';
            html += '<button type="button" id="cur-code-btn" style="width:100%;height:26px;background:#1a1d21;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;padding:0 8px;box-sizing:border-box;display:flex;align-items:center;justify-content:space-between;cursor:pointer">';
            html += '<span id="cur-code-label">' + escapeHtml(firstCode) + '</span>';
            html += '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M6 9l6 6 6-6"/></svg>';
            html += '</button>';
            html += '<div id="cur-code-list" style="display:none;position:absolute;top:100%;left:0;right:0;margin-top:2px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;z-index:200;max-height:200px;overflow-y:auto;scrollbar-width:none">';
            $.each(available, function(_, code) {
                html += '<div class="cur-code-opt" data-value="' + escapeHtml(code) + '" style="padding:5px 8px;font-size:11px;color:#e0e0e0;cursor:pointer">' + escapeHtml(code) + '</div>';
            });
            html += '</div></div></div>';
        } else {
            html += '<input type="hidden" id="cur-code" value="' + escapeHtml(c.code || '') + '">';
        }

        var curPos = c.symbol_position || 'left';
        html += '<div style="margin-bottom:10px">';
        html += '<div style="font-size:11px;color:#888;margin-bottom:3px">Position</div>';
        html += '<div style="display:flex;gap:0">';
        html += '<button type="button" class="cur-pos-btn impulse-btn-sm' + (curPos==='left'||curPos==='left_space' ? ' active' : '') + '" data-pos="left" style="height:26px;box-sizing:border-box;border-radius:3px 0 0 3px;border-right:none;min-width:48px" title="Symbol before amount ($10)">Before</button>';
        html += '<button type="button" class="cur-pos-btn impulse-btn-sm' + (curPos==='right'||curPos==='right_space' ? ' active' : '') + '" data-pos="right" style="height:26px;box-sizing:border-box;border-radius:0 3px 3px 0;min-width:48px" title="Symbol after amount (10€)">After</button>';
        html += '</div>';
        html += '</div>';
        html += '<input type="hidden" id="cur-symbol" value="' + escapeHtml(c.symbol||'') + '">';
        html += '<input type="hidden" id="cur-position" value="' + escapeHtml(curPos) + '">';
        html += '<input type="hidden" id="cur-name" value="' + escapeHtml(c.name||'') + '">';
        html += '<input type="hidden" id="cur-rate" value="' + escapeHtml(String(c.exchange_rate || 1)) + '">';

        html += '<div style="display:flex;gap:6px">';
        html += '<button id="cur-save-btn" type="button" class="impulse-btn-sm" style="color:#e0e0e0;border-color:#555">Save</button>';
        html += '<button id="cur-cancel-btn" type="button" class="impulse-btn-sm">Cancel</button>';
        html += '</div></div>';

        $('#currency-list-wrap').children().first().after(html);

        if (!isEdit) {
            var _known = {
                USD:['US Dollar','$'],EUR:['Euro','€'],GBP:['British Pound','£'],
                CAD:['Canadian Dollar','C$'],AUD:['Australian Dollar','A$'],
                JPY:['Japanese Yen','¥'],CNY:['Chinese Yuan','¥'],INR:['Indian Rupee','₹'],
                MXN:['Mexican Peso','MX$'],BRL:['Brazilian Real','R$'],CHF:['Swiss Franc','CHF'],
                SEK:['Swedish Krona','kr'],NOK:['Norwegian Krone','kr'],DKK:['Danish Krone','kr'],
                PLN:['Polish Zloty','zł'],KRW:['South Korean Won','₩'],SGD:['Singapore Dollar','S$'],
                HKD:['Hong Kong Dollar','HK$'],NZD:['New Zealand Dollar','NZ$'],
                ZAR:['South African Rand','R'],AED:['UAE Dirham','د.إ'],ILS:['Israeli Shekel','₪'],
                THB:['Thai Baht','฿'],PHP:['Philippine Peso','₱'],TWD:['Taiwan Dollar','NT$'],
                TRY:['Turkish Lira','₺'],CZK:['Czech Koruna','Kč'],HUF:['Hungarian Forint','Ft']
            };

            $(document).on('click', '#cur-code-btn', function(e) {
                e.stopPropagation();
                var $list = $('#cur-code-list');
                var open = $list.is(':visible');
                $list.toggle(!open);
            });

            $(document).on('click', '.cur-code-opt', function() {
                var val = $(this).data('value');
                $('#cur-code').val(val);
                $('#cur-code-label').text(val);
                $('#cur-code-list').hide();
                var d = _known[val];
                if (d) { $('#cur-name').val(d[0]); $('#cur-symbol').val(d[1]); }
            });

            $(document).on('mousedown.curcode', function(e) {
                if (!$(e.target).closest('#cur-code-wrap').length) {
                    $('#cur-code-list').hide();
                }
            });

            $(document).on('mouseenter', '.cur-code-opt', function() {
                $(this).css('background','#3a3f44');
            }).on('mouseleave', '.cur-code-opt', function() {
                $(this).css('background','');
            });

            var d0 = _known[$('#cur-code').val()];
            if (d0) { $('#cur-name').val(d0[0]); $('#cur-symbol').val(d0[1]); }
        }
    }

    $(document).on('click', '#currency-add-btn', function() { openCurrencyForm(null); });
    $(document).on('click', '.cur-pos-btn', function() {
        var pos = $(this).data('pos');
        $('#cur-position').val(pos);
        $(this).closest('div').find('.cur-pos-btn').removeClass('active');
        $(this).addClass('active');
    });
    $(document).on('click', '.currency-edit', function() {
        var id = parseInt($(this).data('id'));
        var c  = (window._currencyList || []).filter(function(x) { return parseInt(x.id) === id; })[0];
        if (c) openCurrencyForm(c);
    });
    $(document).on('click', '#cur-cancel-btn', function() { $(document).off('mousedown.curcode'); loadCurrencies(); });

    $(document).on('click', '.currency-set-default', function() {
        var id = $(this).data('id');
        $.ajax({
            url: window.Impulse.api + 'currencies/' + id + '/set-default',
            method: 'POST',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function() { showImpulseToast('Default currency updated'); loadCurrencies(); })
          .fail(function(xhr) { showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Error', 'error'); });
    });

    $(document).on('click', '.currency-delete', function() {
        if (!window.impulseConfirm('Delete this currency?')) return;
        var id = $(this).data('id');
        $.ajax({
            url: window.Impulse.api + 'currencies/' + id,
            method: 'DELETE',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function() { showImpulseToast('Currency deleted'); loadCurrencies(); })
          .fail(function(xhr) { showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Error', 'error'); });
    });

    $(document).on('click', '#cur-save-btn', function() {
        $(document).off('mousedown.curcode');
        var code = $.trim($('#cur-code').val());
        if (!code || code.length !== 3) { showImpulseToast('Invalid currency code', 'error'); return; }
        
        var zeroDecimalCurrencies = ['JPY','KRW','VND','CLP','ISK','UGX','PYG','RWF'];
        var decimals = zeroDecimalCurrencies.indexOf(code.toUpperCase()) !== -1 ? 0 : 2;
        var payload = {
            id:                 $('#cur-id').val(),
            code:               code,
            name:               $('#cur-name').val(),
            symbol:             $('#cur-symbol').val(),
            exchange_rate:      $('#cur-rate').val(),
            decimals:           decimals,
            symbol_position:    $('#cur-position').val(),
            thousand_separator: ',',
            decimal_separator:  '.',
            enabled:            1
        };
        $(this).prop('disabled', true).text('Saving…');
        $.ajax({
            url: window.Impulse.api + 'currencies',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(payload),
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function() { showImpulseToast('Currency saved'); loadCurrencies(); })
          .fail(function(xhr) {
              showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Error', 'error');
              $('#cur-save-btn').prop('disabled', false).text('Save');
          });
    });

    

    var _teamRoles = {};
    var _teamWorkspaces = {};
    var _teamData  = [];
    var _inpStyle  = 'height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:0 8px;font-size:11px;box-sizing:border-box;width:100%;outline:none';

    function loadTeamData() {
        $.ajax({
            url: window.Impulse.api + 'team',
            method: 'GET',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function(res) {
            _teamData       = res.team       || [];
            _teamRoles      = res.roles      || {};
            _teamWorkspaces = res.workspaces || res.roles || {};
            renderTeamList();
        }).fail(function() {
            $('#team-list').html('<div style="text-align:center;color:#555;padding:20px;font-size:11px">Failed to load team</div>');
        });
    }

    function renderTeamList() {
        var currentId   = window.Impulse.currentUser ? window.Impulse.currentUser.id : 0;
        var currentRole = window.Impulse.currentUser ? window.Impulse.currentUser.role : '';
        var isOwner     = (currentRole === 'owner' || currentRole === 'administrator');
        var wsKeys      = Object.keys(_teamWorkspaces || {});
        var html = '';

        $('#team-member-count').text(_teamData.length ? _teamData.length + ' member' + (_teamData.length !== 1 ? 's' : '') : '');

        if (!_teamData.length) {
            html = '<div style="text-align:center;color:#555;padding:20px;font-size:11px">No team members yet. Use + Invite to add people.</div>';
        } else {
            _teamData.forEach(function(u) {
                var isSelf      = (u.id == currentId);
                var isThisOwner = u.is_owner;
                var canEdit     = isOwner && !isThisOwner;
                var uws         = u.workspaces || [];

                html += '<div class="team-member-row" data-uid="' + u.id + '" style="display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid #2a2e33">';

                html += '<div style="flex:1;min-width:0;overflow:hidden">';
                if (canEdit) {
                    html += '<div class="team-name-display" style="cursor:text">';
                    html += '<span style="color:#e0e0e0;font-size:11px;font-weight:500">' + escapeHtml(u.display_name || u.email) + '</span>';
                    if (u.display_name && u.display_name !== u.email) {
                        html += '<br><span style="color:#555;font-size:11px">' + escapeHtml(u.email) + '</span>';
                    }
                    html += '</div>';
                    html += '<div class="team-name-edit" style="display:none">';
                    html += '<input class="team-edit-field" data-field="display_name" data-uid="' + u.id + '" value="' + escapeHtml(u.display_name || '') + '" placeholder="Name" style="' + _inpStyle + ';margin-bottom:3px">';
                    html += '<input class="team-edit-field" data-field="email" data-uid="' + u.id + '" value="' + escapeHtml(u.email || '') + '" placeholder="Email" style="' + _inpStyle + '">';
                    html += '</div>';
                } else {
                    html += '<span style="color:#e0e0e0;font-size:11px;font-weight:500">' + escapeHtml(u.display_name || u.email) + '</span>';
                    if (u.display_name && u.display_name !== u.email) {
                        html += '<br><span style="color:#555;font-size:11px">' + escapeHtml(u.email) + '</span>';
                    }
                    if (isSelf) html += ' <span style="color:#555;font-size:11px">(you)</span>';
                }
                html += '</div>';

                if (isThisOwner) {
                    html += '<span style="font-size:11px;color:#555;flex-shrink:0">Full access</span>';
                } else {
                    wsKeys.forEach(function(ws) {
                        var checked = uws.indexOf(ws) !== -1 ? ' checked' : '';
                        var disabled = !canEdit ? ' disabled' : '';
                        html += '<label style="display:flex;align-items:center;gap:3px;font-size:11px;color:#888;cursor:' + (canEdit ? 'pointer' : 'default') + ';flex-shrink:0" title="' + escapeHtml(_teamWorkspaces[ws]) + '">';
                        html += '<input type="checkbox" class="team-ws-check" data-uid="' + u.id + '" data-ws="' + ws + '"' + checked + disabled + ' style="margin:0">';
                        html += _teamWorkspaces[ws];
                        html += '</label>';
                    });
                }

                if (isOwner && !isThisOwner && !isSelf) {
                    html += '<button class="team-revoke-btn impulse-btn-sm" data-uid="' + u.id + '" style="height:26px;padding:0 8px;flex-shrink:0">Remove</button>';
                }

                html += '</div>';
            });
        }
        $('#team-list').html(html);
    }

    $(document).on('click', '.team-name-display', function() {
        var $td = $(this).closest('td');
        $(this).hide();
        $td.find('.team-name-edit').show();
        $td.find('.team-edit-field').first().focus().select();
    });

    
    $(document).on('blur', '.team-edit-field', function() {
        var $inp  = $(this);
        var $td   = $inp.closest('td');
        var uid   = parseInt($inp.data('uid'), 10);
        var field = $inp.data('field');
        var val   = $.trim($inp.val());
        var u     = null;
        for (var i = 0; i < _teamData.length; i++) { if (_teamData[i].id == uid) { u = _teamData[i]; break; } }
        if (!u) return;

        setTimeout(function() {
            
            if ($td.find('.team-edit-field:focus').length) return;

            var nameVal  = $.trim($td.find('[data-field="display_name"]').val());
            var emailVal = $.trim($td.find('[data-field="email"]').val());
            var changed  = (nameVal !== (u.display_name || '')) || (emailVal !== (u.email || ''));

            $td.find('.team-name-edit').hide();
            $td.find('.team-name-display').show();

            if (!changed) return;

            var payload = { display_name: nameVal, email: emailVal };
            $.ajax({
                url: window.Impulse.api + 'team/' + uid,
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(payload),
                beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
            }).done(function() {
                u.display_name = nameVal;
                u.email        = emailVal;
                renderTeamList();
            }).fail(function(xhr) {
                showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Save failed', 'error');
            });
        }, 100);
    });

    $(document).on('keydown', '.team-edit-field', function(e) {
        if (e.key === 'Enter')  { $(this).blur(); e.preventDefault(); }
        if (e.key === 'Escape') {
            var $td = $(this).closest('td');
            $td.find('.team-name-edit').hide();
            $td.find('.team-name-display').show();
        }
    });

    $(document).on('change', '.team-ws-check', function() {
        var uid = $(this).data('uid');
        var workspaces = [];
        $('.team-ws-check[data-uid="' + uid + '"]:checked').each(function() {
            workspaces.push($(this).data('ws'));
        });
        $.ajax({
            url: window.Impulse.api + 'team/' + uid + '/role',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ workspaces: workspaces }),
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function() { showImpulseToast('Access updated'); })
          .fail(function(xhr) { showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Error', 'error'); loadTeamData(); });
    });

    $(document).on('click', '.team-revoke-btn', function() {
        var uid = $(this).data('uid');
        if (!window.impulseConfirm('Remove this person from the team?')) return;
        $.ajax({
            url: window.Impulse.api + 'team/' + uid + '/revoke',
            method: 'POST',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function() { showImpulseToast('Member removed'); loadTeamData(); })
          .fail(function(xhr) { showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Error', 'error'); });
    });

    $(document).on('click', '#team-add-btn', function() {
        var wsKeys = Object.keys(_teamWorkspaces || {});
        var html = '<div style="background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;padding:8px 10px;margin-bottom:8px" id="team-invite-form">';
        html += '<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">';
        html += '<input type="email" id="team-invite-email" placeholder="Email address" style="flex:1;min-width:120px;height:26px;background:#1a1d21;border:1px solid #3a3f44;color:#e0e0e0;padding:0 8px;font-size:11px;border-radius:3px;box-sizing:border-box">';
        wsKeys.forEach(function(ws) {
            html += '<label style="display:flex;align-items:center;gap:3px;font-size:11px;color:#888;cursor:pointer;flex-shrink:0">';
            html += '<input type="checkbox" class="team-invite-ws" value="' + ws + '" style="margin:0">';
            html += (_teamWorkspaces[ws] || ws);
            html += '</label>';
        });
        html += '<button id="team-invite-send" type="button" class="impulse-btn-sm" style="height:26px;padding:0 10px;flex-shrink:0">Add</button>';
        html += '<button id="team-invite-cancel" type="button" class="impulse-btn-sm" style="height:26px;padding:0 10px;flex-shrink:0">Cancel</button>';
        html += '</div></div>';
        $('#team-list').prepend(html);
        $('#team-invite-email').focus();
    });

    $(document).on('click', '#team-invite-cancel', function() { loadTeamData(); });

    $(document).on('click', '#team-invite-send', function() {
        var email = $.trim($('#team-invite-email').val());
        var workspaces = [];
        $('.team-invite-ws:checked').each(function() { workspaces.push($(this).val()); });
        if (!email) { showImpulseToast('Enter an email address', 'error'); return; }
        if (!workspaces.length) { showImpulseToast('Select at least one workspace', 'error'); return; }
        $(this).prop('disabled', true).text('Adding...');
        $.ajax({
            url: window.Impulse.api + 'team/invite',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ email: email, workspaces: workspaces }),
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function(res) {
            showImpulseToast(res.message || 'Added');
            loadTeamData();
        }).fail(function(xhr) {
            showImpulseToast((xhr.responseJSON && xhr.responseJSON.error) || 'Error', 'error');
            $('#team-invite-send').prop('disabled', false).text('Add');
        });
    });

    function timeAgo(dateStr) {
        var d    = new Date(dateStr.replace(' ', 'T') + 'Z');
        var secs = Math.floor((Date.now() - d.getTime()) / 1000);
        if (secs < 60)   return 'just now';
        if (secs < 3600) return Math.floor(secs/60) + 'm ago';
        if (secs < 86400) return Math.floor(secs/3600) + 'h ago';
        return Math.floor(secs/86400) + 'd ago';
    }

    

    $(document).on('click', '#sync-users-btn', function() {
        var $btn = $(this);
        var $res = $('#sync-users-result');
        $btn.prop('disabled', true).text('Syncing...');
        $res.hide();
        $.ajax({
            url: window.Impulse.api + 'migration/sync-users',
            method: 'POST',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', window.Impulse.nonce); }
        }).done(function(res) {
            $res.text(res.message || 'Done.').show();
            $btn.prop('disabled', false).text('Sync Users to Standalone');
        }).fail(function(xhr) {
            var msg = (xhr.responseJSON && xhr.responseJSON.error) ? xhr.responseJSON.error : 'Sync failed. Check server logs.';
            $res.text(msg).show();
            $btn.prop('disabled', false).text('Sync Users to Standalone');
        });
    });

    function loadLoyaltySettings() {
        
        $.post(ajaxurl, { action: 'instinctor_get_loyalty_stats', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) return;
            var d = res.data;
            var html = '';
            html += '<span style="font-size:11px;color:#888">Members: <strong style="color:#e0e0e0">' + d.members + '</strong></span>';
            html += '<span style="font-size:11px;color:#555">·</span>';
            html += '<span style="font-size:11px;color:#888">Points issued: <strong style="color:#e0e0e0">' + d.active_points.toLocaleString() + '</strong></span>';
            html += '<span style="font-size:11px;color:#555">·</span>';
            html += '<span style="font-size:11px;color:#888">Redeemed: <strong style="color:#e0e0e0">' + d.redeemed.toLocaleString() + '</strong></span>';
            $('#loyalty-stats-row').html(html).css({'display':'flex','align-items':'center','gap':'6px','flex-wrap':'wrap','margin-bottom':'12px'});
        });

        $.post(ajaxurl, { action: 'instinctor_get_loyalty_settings', nonce: window.Impulse.adminNonce }, function(res) {
            if (!res.success) { $('#loyalty-form').html('<div style="color:#555;font-size:11px;padding:12px 0\">Failed to load settings</div>'); return; }
            var s = res.data.settings;

            var row = function(label, inputHtml) {
                return '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px">'
                    + '<span style="font-size:11px;color:#999">' + label + '</span>'
                    + inputHtml
                    + '</div>';
            };
            var numInput = function(id, val, step) {
                step = step || '1';
                return '<input id="' + id + '" type="number" value="' + val + '" step="' + step + '" style="width:72px;height:26px;background:#2a2e33;border:1px solid #3a3f44;color:#e0e0e0;padding:0 6px;font-size:11px;border-radius:3px;text-align:right;box-sizing:border-box">';
            };
            var secLabel = function(txt) {
                return '<div style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:0.5px;margin:10px 0 6px">' + txt + '</div>';
            };

            var html = '';

            html += '<div style="display:flex;margin-bottom:10px">';
            html += '<button type="button" class="impulse-btn-sm loyalty-status-btn' + (s.enabled ? ' active' : '') + '" data-status="active" style="border-radius:3px 0 0 3px;flex:1">Active</button>';
            html += '<button type="button" class="impulse-btn-sm loyalty-status-btn' + (!s.enabled ? ' active' : '') + '" data-status="inactive" style="border-radius:0 3px 3px 0;flex:1">Inactive</button>';
            html += '</div>';

            html += secLabel('Points');
            html += row('Points per $1 spent',        numInput('loyalty-ppd',  s.points_per_dollar, '0.1'));
            html += row('$ value per point',           numInput('loyalty-pv',   s.points_value, '0.001'));
            html += row('Min points to redeem',        numInput('loyalty-minr', s.min_redeem));

            html += secLabel('Bonus points');
            html += row('Signup bonus',                numInput('loyalty-sp',  s.signup_points));
            html += row('Referral bonus',              numInput('loyalty-ref', s.referral_points));

            html += secLabel('Expiry');
            html += row('Days until expiry (0 = never)', numInput('loyalty-exp', s.expiry_days));

            html += secLabel('Tiers');
            var tiers = [
                { name: 'Bronze',   min: '0+',      mult: '1.0×' },
                { name: 'Silver',   min: '1,000+',  mult: '1.25×' },
                { name: 'Gold',     min: '5,000+',  mult: '1.5×' },
                { name: 'Platinum', min: '15,000+', mult: '2.0×' }];
            html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:12px">';
            tiers.forEach(function(t) {
                html += '<div style="background:#2a2e33;border-radius:4px;padding:8px 10px">';
                html += '<div style="font-size:11px;color:#e0e0e0;font-weight:600;margin-bottom:3px">' + t.name + '</div>';
                html += '<div style="font-size:11px;color:#888">' + t.min + ' pts</div>';
                html += '<div style="font-size:11px;color:#999;margin-top:2px">' + t.mult + ' earn rate</div>';
                html += '</div>';
            });
            html += '</div>';

            html += '<button type="button" id="loyalty-save-btn" class="impulse-btn-sm" style="width:100%">Save Settings</button>';
            $('#loyalty-form').html(html);
        });
    }

    $(document).on('click', '#loyalty-save-btn', function() {
        var $btn = $(this).prop('disabled', true).text('Saving…');
        $.post(ajaxurl, {
            action: 'instinctor_save_loyalty_settings',
            nonce: window.Impulse.adminNonce,
            enabled:          $('.loyalty-status-btn.active').data('status') === 'active' ? 1 : 0,
            points_per_dollar: $('#loyalty-ppd').val(),
            points_value:     $('#loyalty-pv').val(),
            min_redeem:       $('#loyalty-minr').val(),
            signup_points:    $('#loyalty-sp').val(),
            referral_points:  $('#loyalty-ref').val(),
            expiry_days:      $('#loyalty-exp').val()
        }, function(res) {
            $btn.prop('disabled', false).text('Save Settings');
            if (res.success) showImpulseToast('Loyalty settings saved');
            else showImpulseToast(res.data.message || 'Save failed', 'error');
        });
    });

    

    var gcLoaded = false;

    function loadGiftCards() {
        var status = $('#gc-filter-status').val();
        $('#gc-list').html('<li class="impulse-empty"><div class="impulse-empty-title" style="font-size:11px;color:#555">Loading...</div></li>');
        $.post(ajaxurl, { action: 'instinctor_get_gift_cards', nonce: window.Impulse.adminNonce, status: status }, function(res) {
            if (!res.success) { $('#gc-list').html('<li class="impulse-empty"><div class="impulse-empty-title">Failed to load</div></li>'); return; }
            var cards = res.data.cards;
            if (!cards.length) {
                $('#gc-list').html('<li class="impulse-empty"><div class="impulse-empty-icon"><svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg></div><div class="impulse-empty-title">No gift cards</div><div class="impulse-empty-desc">Create your first gift card.</div></li>');
                return;
            }
            var html = '';
            cards.forEach(function(c) {
                var statusColor = c.status === 'active' ? '#e0e0e0' : c.status === 'depleted' ? '#555' : '#3a3f44';
                html += '<li class="impulse-list-item" data-gc-id="' + c.id + '">';
                html += '<div class="impulse-list-item-content">';
                html += '<div class="impulse-list-item-title" style="font-family:monospace">' + escapeHtml(c.code) + '</div>';
                html += '<div class="impulse-list-item-subtitle" style="color:#888">';
                if (c.recipient_name) html += escapeHtml(c.recipient_name) + ' · ';
                html += c.current_balance + ' remaining · Exp: ' + c.expires_at;
                html += '</div></div>';
                html += '<span class="impulse-list-item-meta" style="color:' + statusColor + '">' + ucFirst(c.status) + '</span>';
                html += '</li>';
            });
            $('#gc-list').html(html);
        });
    }

    

    $(document).on('change', '#gc-filter-status', function() { loadGiftCards(); });

    $(document).on('click', '#gc-list .impulse-list-item', function() {
        $('#gc-list .impulse-list-item').removeClass('active');
        $(this).addClass('active');
        var id = $(this).data('gc-id');
        showGiftCardDetail(id);
    });

    function showGiftCardDetail(id) {
        $('#settings-detail-content').html('<div style="font-size:11px;color:#555;padding:16px">Loading...</div>');
        $.post(ajaxurl, { action: 'instinctor_get_gift_card_detail', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (!res.success) { $('#settings-detail-content').html('<div style="font-size:11px;color:#e74c3c;padding:16px">Failed to load</div>'); return; }
            var c = res.data;
            var statusColor = c.status === 'active' ? '#e0e0e0' : c.status === 'depleted' ? '#555' : '#3a3f44';

            var html = '';
            
            html += '<div style="margin-bottom:12px">';
            html += '<div style="font-weight:600;color:#e0e0e0;font-family:monospace;margin-bottom:4px">' + escapeHtml(c.code) + '</div>';
            html += '<span class="impulse-status" style="color:' + statusColor + '">' + ucFirst(c.status) + '</span>';
            html += '</div>';

            html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:12px">';
            html += '<div style="background:#2a2e33;border-radius:4px;padding:8px">';
            html += '<div style="font-size:11px;color:#888;margin-bottom:2px">Original</div>';
            html += '<div style="font-weight:600;color:#e0e0e0">' + c.initial_balance + '</div></div>';
            html += '<div style="background:#2a2e33;border-radius:4px;padding:8px">';
            html += '<div style="font-size:11px;color:#888;margin-bottom:2px">Remaining</div>';
            html += '<div style="font-weight:600;color:#e0e0e0">' + c.current_balance + '</div></div>';
            html += '</div>';

            if (c.recipient_name || c.recipient_email) {
                html += '<div style="margin-bottom:10px">';
                html += '<div style="font-size:11px;color:#888;margin-bottom:3px">Recipient</div>';
                if (c.recipient_name) html += '<div style="font-size:11px;color:#e0e0e0">' + escapeHtml(c.recipient_name) + '</div>';
                if (c.recipient_email) html += '<div style="font-size:11px;color:#999">' + escapeHtml(c.recipient_email) + '</div>';
                html += '</div>';
            }

            if (c.message) {
                html += '<div style="margin-bottom:10px">';
                html += '<div style="font-size:11px;color:#888;margin-bottom:3px">Message</div>';
                html += '<div style="font-size:11px;color:#999;font-style:italic">' + escapeHtml(c.message) + '</div>';
                html += '</div>';
            }

            html += '<div style="font-size:11px;color:#888;margin-bottom:12px">Expires: ' + c.expires_at + ' · Created: ' + c.created_at + '</div>';

            if (c.transactions && c.transactions.length) {
                html += '<div style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px">Transactions</div>';
                html += '<div style="background:#2a2e33;border-radius:4px;overflow:hidden;margin-bottom:12px">';
                c.transactions.forEach(function(t) {
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:6px 10px;border-bottom:1px solid #1a1d21">';
                    html += '<span style="font-size:11px;color:#999">' + escapeHtml(t.note || t.type) + '</span>';
                    html += '<span style="font-size:11px;color:#e0e0e0">' + t.amount + '</span>';
                    html += '</div>';
                });
                html += '</div>';
            }

            html += '<div style="display:flex;flex-direction:column;gap:6px">';
            if (c.recipient_email) {
                html += '<button type="button" class="impulse-btn-sm" id="gc-resend-btn" data-id="' + c.id + '" style="width:100%">Resend Email</button>';
            }
            if (c.status === 'active') {
                html += '<button type="button" class="impulse-btn-sm" id="gc-deactivate-btn" data-id="' + c.id + '" style="width:100%;color:#ef4444;border-color:#ef4444">Deactivate</button>';
            }
            html += '</div>';

            $('#settings-detail-content').html(html);
        });
    }

    $(document).on('click', '#gc-create-btn', function() {
        $('#gc-list .impulse-list-item').removeClass('active');
        showGiftCardCreateForm();
    });

    function showGiftCardCreateForm() {
        var currency = window.Impulse.products ? window.Impulse.products.currency : '$';
        var html = '';
        html += '<div style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:10px">New Gift Card</div>';

        var field = function(id, label, type, placeholder) {
            type = type || 'text';
            return '<div style="margin-bottom:8px">'
                + '<div style="font-size:11px;color:#999;margin-bottom:3px">' + label + '</div>'
                + '<input id="' + id + '" type="' + type + '" placeholder="' + (placeholder||'') + '" style="width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;color:#e0e0e0;padding:0 6px;font-size:11px;border-radius:3px;box-sizing:border-box">'
                + '</div>';
        };

        html += field('gc-new-amount', 'Amount (' + currency + ')', 'number', '25.00');
        html += field('gc-new-recipient-name', 'Recipient name', 'text', 'Jane Smith');
        html += field('gc-new-recipient-email', 'Recipient email', 'email', 'jane@example.com');
        html += field('gc-new-sender', 'From', 'text', 'Your Store');
        html += '<div style="margin-bottom:8px">';
        html += '<div style="font-size:11px;color:#999;margin-bottom:3px">Message (optional)</div>';
        html += '<textarea id="gc-new-message" rows="3" placeholder="Happy birthday!" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;color:#e0e0e0;padding:6px;font-size:11px;border-radius:3px;box-sizing:border-box;resize:vertical"></textarea>';
        html += '</div>';
        html += field('gc-new-expiry', 'Expires in (days, 0 = never)', 'number', '365');
        html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer;margin-bottom:12px">';
        html += '<input type="checkbox" id="gc-new-send-now" checked style="margin:0"> <span style="font-size:11px;color:#e0e0e0">Send email immediately</span>';
        html += '</label>';
        html += '<button type="button" id="gc-save-new-btn" class="impulse-btn-sm impulse-btn-primary" style="width:100%">Create Gift Card</button>';

        $('#settings-detail-content').html(html);
    }

    $(document).on('click', '#gc-save-new-btn', function() {
        var $btn = $(this).prop('disabled', true).text('Creating…');
        $.post(ajaxurl, {
            action: 'instinctor_create_gift_card',
            nonce: window.Impulse.adminNonce,
            amount:          $('#gc-new-amount').val(),
            recipient_name:  $('#gc-new-recipient-name').val(),
            recipient_email: $('#gc-new-recipient-email').val(),
            sender_name:     $('#gc-new-sender').val(),
            message:         $('#gc-new-message').val(),
            expires_days:    $('#gc-new-expiry').val(),
            send_now:        $('#gc-new-send-now').is(':checked') ? 1 : 0
        }, function(res) {
            $btn.prop('disabled', false).text('Create Gift Card');
            if (res.success) {
                showImpulseToast('Gift card created: ' + res.data.code);
                gcLoaded = false;
                loadGiftCards();
                showGiftCardDetail(res.data.id);
            } else {
                showImpulseToast(res.data.message || 'Failed to create', 'error');
            }
        });
    });

    $(document).on('click', '#gc-resend-btn', function() {
        var id = $(this).data('id');
        var $btn = $(this).prop('disabled', true).text('Sending…');
        $.post(ajaxurl, { action: 'instinctor_send_gift_card', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            $btn.prop('disabled', false).text('Resend Email');
            if (res.success) showImpulseToast('Email sent');
            else showImpulseToast(res.data.message || 'Failed to send', 'error');
        });
    });

    $(document).on('click', '#gc-deactivate-btn', function() {
        if (!window.impulseConfirm('Deactivate this gift card? It will no longer be usable.')) return;
        var id = $(this).data('id');
        var $btn = $(this).prop('disabled', true).text('Deactivating…');
        $.post(ajaxurl, { action: 'instinctor_deactivate_gift_card', nonce: window.Impulse.adminNonce, id: id }, function(res) {
            if (res.success) {
                showImpulseToast('Gift card deactivated');
                gcLoaded = false;
                loadGiftCards();
                $('#settings-detail-content').html('');
            } else {
                $btn.prop('disabled', false).text('Deactivate');
                showImpulseToast(res.data.message || 'Failed', 'error');
            }
        });
    });

    function ucFirst(str) { return str ? str.charAt(0).toUpperCase() + str.slice(1) : ''; }

    

    
    $(document).on('click', '#aftership-save-btn', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('Saving...');
        
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_save_aftership',
            nonce: window.Impulse.adminNonce,
            enabled: $('#aftership-enabled').is(':checked') ? 1 : 0,
            api_key: $('#aftership-api-key').val(),
            update_frequency: $('#aftership-frequency').val()
        }, function(response) {
            $btn.prop('disabled', false).text('Save Settings');
            if (response.success) {
                showToast('AfterShip settings saved');
                window.Impulse.aftershipSettings = response.data.settings;
            } else {
                showToast(response.data?.message || 'Error saving settings', 'error');
            }
        });
    });
    
    $(document).on('click', '#aftership-test-btn', function() {
        var $btn = $(this);
        var originalText = $btn.text();
        $btn.prop('disabled', true).text('Testing...');
        
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_test_aftership',
            nonce: window.Impulse.adminNonce,
            api_key: $('#aftership-api-key').val()
        }, function(response) {
            $btn.prop('disabled', false).text(originalText);
            if (response.success) {
                showToast('Connection successful! ' + response.data.carriers_count + ' carriers available.');
            } else {
                showToast(response.data?.message || 'Connection failed', 'error');
            }
        });
    });
    
    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    function bindStatusFilters() {
        
        $('input[name="order_status_filter"]').on('change', function() {
            currentStatusFilter = $(this).val();
            $(this).closest('.impulse-filter-section').find('.impulse-filter-option').removeClass('active');
            $(this).closest('.impulse-filter-option').addClass('active');
            reloadOrdersList();
        });

    }

    

    var ORDERS_BATCH      = 50;
    var ordersOffset      = 0;
    var ordersLoading     = false;
    var ordersExhausted   = false;
    var ordersSortBy      = 'date';
    var ordersSortDir     = 'DESC';

    function buildOrderRow(o) {
        var showDate  = $('#col-show-date').is(':checked');
        var html = '<li class="impulse-list-item" data-order-id="' + o.id + '" data-status="' + escapeHtml(o.status) + '"' + (o.customer_id ? ' data-customer-id="' + o.customer_id + '"' : '') + '>';
        html += '<span class="impulse-list-order-num">#' + escapeHtml(o.order_number) + '</span>';
        html += '<span class="impulse-list-order-customer">' + escapeHtml(o.customer) + '</span>';
        html += '<span class="impulse-status impulse-status-' + escapeHtml(o.status) + '">' + escapeHtml(o.status.charAt(0).toUpperCase() + o.status.slice(1)) + '</span>';
        html += '<span class="impulse-list-order-age">' + escapeHtml(showDate ? o.date : o.time_ago) + '</span>';
        html += '<span class="impulse-list-order-total">' + escapeHtml(o.total) + '</span>';
        html += '</li>';
        return html;
    }

    function fetchOrders(offset, append) {
        if (ordersLoading) return;

        

        var $list = $('#dashboard-orders-list');
        if (!$list.length) return;

        ordersLoading = true;

        if (!append) {
            $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Loading orders...</li>');
        } else {
            $list.find('#orders-load-more-sentinel').remove();
            $list.append('<li id="orders-loading-indicator" style="padding:10px;text-align:center;color:#555;font-size:11px">Loading...</li>');
        }

        $.post(ajaxurl, {
            action:  'instinctor_get_orders_list',
            nonce:   window.Impulse.adminNonce,
            offset:  offset,
            status:  currentStatusFilter === 'all' ? '' : currentStatusFilter,
            search:  _ordersSearchQuery || '',
            sort_by: ordersSortBy,
            sort_dir: ordersSortDir
        }, function(r) {
            ordersLoading = false;
            if (!r.success) return;
            var data = r.data;

            $list.find('#orders-loading-indicator').remove();

            if (!append) {
                
                if (data.orders.length === 0) {
                    $list.html('<li style="display:flex;align-items:center;justify-content:center;height:100%;min-height:220px"><svg viewBox="0 0 24 24" width="48" height="48" color="currentColor" style="opacity:0.12"><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></li>');
                } else {
                    var html = '';
                    data.orders.forEach(function(o) { html += buildOrderRow(o); });
                    $list.html(html);
                }

                if (data.status_counts) {
                    var counts = data.status_counts;
                    $('input[name="order_status_filter"]').each(function() {
                        var val = $(this).val();
                        $(this).closest('label').find('.impulse-filter-count').text(counts[val] || 0);
                    });
                }
                if (data.finance) {
                    var f = data.finance, cur = data.currency;
                    $('.impulse-stat-item').each(function() {
                        var lbl = $(this).find('.impulse-stat-label').text().toLowerCase();
                        if (lbl === 'today')   $(this).find('.impulse-stat-num').text(cur + (f.today_revenue || 0).toFixed(0));
                        if (lbl === 'orders')  $(this).find('.impulse-stat-num').text(f.today_orders || 0);
                        if (lbl === 'month')   $(this).find('.impulse-stat-num').text(cur + (f.month_revenue || 0).toFixed(0));
                        if (lbl === 'pending' && data.status_counts) $(this).find('.impulse-stat-num').text(data.status_counts.pending || 0);
                    });
                }
            } else {
                
                var html = '';
                data.orders.forEach(function(o) { html += buildOrderRow(o); });
                $list.append(html);
            }

            ordersOffset   = offset + data.orders.length;
            ordersExhausted = !data.has_more;

            if (!ordersExhausted) {
                $list.append('<li id="orders-load-more-sentinel" style="height:1px;visibility:hidden"></li>');
            }
        }).fail(function() {
            ordersLoading = false;
            $('#orders-loading-indicator').remove();
        });
    }

    function reloadOrdersList() {
        ordersOffset    = 0;
        ordersExhausted = false;
        fetchOrders(0, false);
    }

    $('#dashboard-orders-list').on('scroll', function() {
        if (ordersLoading || ordersExhausted) return;
        var $list     = $(this);
        var $sentinel = $list.find('#orders-load-more-sentinel');
        if (!$sentinel.length) return;
        var listBottom     = $list.scrollTop() + $list.outerHeight();
        var sentinelOffset = $sentinel.position().top + $list.scrollTop();
        if (listBottom >= sentinelOffset - 100) {
            fetchOrders(ordersOffset, true);
        }
    });

    window.reloadOrdersList = reloadOrdersList;

    reloadOrdersList();

    $(document).on('change', '#col-show-date', function() {
        reloadOrdersList();
    });

    $(document).on('click', '.orders-sort-col', function() {
        var col = $(this).data('sort');
        if (ordersSortBy === col) {
            ordersSortDir = ordersSortDir === 'DESC' ? 'ASC' : 'DESC';
        } else {
            ordersSortBy = col;
            ordersSortDir = col === 'total' ? 'DESC' : (col === 'customer' ? 'ASC' : 'DESC');
        }
        
        $('#orders-sort-header .orders-sort-col').removeClass('active').find('.sort-arrow').remove();
        var arrowClass = ordersSortDir === 'ASC' ? 'asc' : 'desc';
        $(this).addClass('active').append(' <svg width="8" height="8" viewBox="0 0 8 8" fill="currentColor" class="sort-arrow ' + arrowClass + '"><path d="M4 6L1 2h6z"/></svg>');
        reloadOrdersList();
    });

    function filterOrders() {
        
        $('#dashboard-orders-list .impulse-list-item[data-order-id]').each(function() {
            var orderStatus = $(this).data('status');
            if (currentStatusFilter === 'all' || orderStatus === currentStatusFilter) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }
    
    function bindItemSelection() {
        
        $(document).on('click', '#dashboard-orders-list .impulse-list-item[data-order-id]', function(e) {
            if ($(e.target).closest('.impulse-status').length) return;
            selectItem('order', $(this).data('order-id'), $(this));
            loadOrderDetail($(this).data('order-id'));
        });

        $(document).on('click', '#dashboard-coupons-list .impulse-list-item[data-coupon-id]', function() {
            selectItem('coupon', $(this).data('coupon-id'), $(this));
            showCouponDetail($(this));
        });

        $(document).on('click', '[data-for="returns"] .impulse-list-item[data-rma-id]', function() {
            selectItem('rma', $(this).data('rma-id'), $(this));
            showRMADetail($(this));
        });

        $(document).on('click', '[data-for="bookings"] .impulse-list-item[data-booking-id]', function() {
            selectItem('booking', $(this).data('booking-id'), $(this));
            showBookingDetail($(this));
        });

        $(document).on('click', '#dashboard-orders-list, #dashboard-coupons-list, #clients-center-list, [data-for="returns"], [data-for="bookings"]', function(e) {
            if ($(e.target).closest('.impulse-list-item').length) return;
            selectedItemId = null;
            selectedItemType = null;
            $('[data-workspace="store"] .impulse-panel-center .impulse-list-item').removeClass('active');
            $('#order-detail-header').hide();
            $('#clients-right-header').hide();
            $('#dashboard-detail-content').html('');
            $('#customer-detail-content').html('');
            storeRightCollapse();
        });

    }
    
    function selectItem(type, id, $el) {
        if (selectedItemId === id && selectedItemType === type) return;
        selectedItemId = id;
        selectedItemType = type;

        $('[data-workspace="store"] .impulse-panel-center .impulse-list-item').removeClass('active');
        $el.addClass('active');
    }
    
    var _ordersSearchQuery = '';
    function bindSearch() {
        var searchTimeout;
        $('#impulse-orders-search').on('input', function() {
            clearTimeout(searchTimeout);
            var q = $(this).val().trim();
            searchTimeout = setTimeout(function() {
                _ordersSearchQuery = q;
                reloadOrdersList();
            }, 300);
        });
    }

    (function() {
        var _storeSwatchTimer = null;

        function buildStoreColorPicker($swatch, value) {
            if (!value || value.indexOf('#') !== 0 || value.length < 7) value = '#555555';
            var r = parseInt(value.substr(1,2),16)||0, g = parseInt(value.substr(3,2),16)||0, b = parseInt(value.substr(5,2),16)||0;
            var max=Math.max(r,g,b), min=Math.min(r,g,b), h=0, s=0, v=max/255, 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), sat=Math.round(s*100), val=Math.round(v*100);
            var html = '<div class="impulse-color-picker impulse-store-picker" data-hue="'+hue+'" data-sat="'+sat+'" data-val="'+val+'" data-alpha="100" style="position:fixed;z-index:1000040">';
            html += '<div class="impulse-picker-gradient" style="background-color:hsl('+hue+',100%,50%)">';
            html += '<div class="impulse-picker-cursor" style="left:'+sat+'%;top:'+(100-val)+'%"></div></div>';
            html += '<div class="impulse-picker-sliders"><div class="impulse-picker-slider-row">';
            html += '<div class="impulse-picker-hue"><div class="impulse-picker-thumb" style="left:'+((hue/360)*100)+'%"></div></div>';
            html += '</div></div>';
            html += '<div class="impulse-picker-palette" data-default="'+value+'"><div class="impulse-picker-palette-actions">';
            html += '<button type="button" class="impulse-picker-reset store-picker-reset" title="Reset"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg></button>';
            html += '</div></div></div>';
            $swatch.after(html);
        }

        function positionStorePicker($picker, $swatch) {
            var pw = 172, ph = 176;
            var $panel = $swatch.closest('.impulse-store-right-content');
            var panelRect = $panel.length ? $panel[0].getBoundingClientRect() : null;
            var swatchRect = $swatch[0].getBoundingClientRect();
            
            var left = panelRect ? (panelRect.right - pw) : (swatchRect.right - pw);
            var top  = swatchRect.top - 10;
            
            if (top + ph > window.innerHeight - 8) top = swatchRect.bottom - ph + 10;
            top = Math.max(8, Math.min(top, window.innerHeight - ph - 8));
            left = Math.max(8, Math.min(left, window.innerWidth - pw - 8));
            $picker.css({ top: top, left: left, width: pw });
        }

        function applyStorePickerColor($picker) {
            var hue=parseInt($picker.data('hue'))||0, sat=parseInt($picker.data('sat'))||0, val=parseInt($picker.data('val'))||0;
            var h=hue/360, s=sat/100, v=val/100;
            var r,g,b, i=Math.floor(h*6), f=h*6-i, p=v*(1-s), q=v*(1-f*s), 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;}
            var hex='#'+((1<<24)+(Math.round(r*255)<<16)+(Math.round(g*255)<<8)+Math.round(b*255)).toString(16).slice(1);
            $picker.find('.impulse-picker-gradient').css('background-color','hsl('+hue+',100%,50%)');
            var $row=$picker.closest('.impulse-color-row');
            $row.find('.impulse-color-swatch').css('--swatch-color', hex);
            $row.find('.impulse-color-text').val(hex).trigger('change');
        }

        

        
        
        $(document).on('click', '.impulse-store-right-content .impulse-color-swatch', function(e) {
            if ($(this).closest('#settings-chat-panel').length) return;
            e.stopPropagation();
            var $swatch = $(this);
            var $row    = $swatch.closest('.impulse-color-row');
            var $picker = $row.find('.impulse-store-picker');

            if (!$picker.length) {
                var value = $row.find('.impulse-color-text').val() || '#555555';
                buildStoreColorPicker($swatch, value);
                $picker = $row.find('.impulse-store-picker');
            }

            var wasOpen = $picker.hasClass('open');
            $('.impulse-store-picker').removeClass('open');
            if (wasOpen) return;

            clearTimeout(_storeSwatchTimer);
            _storeSwatchTimer = setTimeout(function() {
                positionStorePicker($picker, $swatch);
                $picker.addClass('open');
            }, 0);
        });

        $(document).on('mousedown', '.impulse-store-picker .impulse-picker-gradient', function(e) {
            e.preventDefault();
            var $gradient = $(this);
            var $picker   = $gradient.closest('.impulse-store-picker');
            var $cursor   = $gradient.find('.impulse-picker-cursor');
            function drag(ev) {
                var rect = $gradient[0].getBoundingClientRect();
                var x = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width));
                var y = Math.max(0, Math.min(1, (ev.clientY - rect.top)  / rect.height));
                $cursor.css({ left:(x*100)+'%', top:(y*100)+'%' });
                $picker.data('sat', Math.round(x*100)).data('val', Math.round((1-y)*100));
                applyStorePickerColor($picker);
            }
            drag(e);
            $(document).on('mousemove.storegradient', drag);
            $(document).on('mouseup.storegradient', function() { $(document).off('.storegradient'); });
        });

        $(document).on('mousedown', '.impulse-store-picker .impulse-picker-hue', function(e) {
            e.preventDefault();
            var $hue    = $(this);
            var $picker = $hue.closest('.impulse-store-picker');
            var $thumb  = $hue.find('.impulse-picker-thumb');
            function drag(ev) {
                var rect = $hue[0].getBoundingClientRect();
                var x = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width));
                $thumb.css('left', (x*100)+'%');
                $picker.data('hue', Math.round(x*360));
                applyStorePickerColor($picker);
            }
            drag(e);
            $(document).on('mousemove.storehue', drag);
            $(document).on('mouseup.storehue', function() { $(document).off('.storehue'); });
        });

        $(document).on('click', '.store-picker-reset', function(e) {
            e.stopPropagation();
            var $picker = $(this).closest('.impulse-store-picker');
            var def = $picker.find('.impulse-picker-palette').data('default') || '#555555';
            
            var r=parseInt(def.substr(1,2),16)||0, g=parseInt(def.substr(3,2),16)||0, b=parseInt(def.substr(5,2),16)||0;
            var max=Math.max(r,g,b),min=Math.min(r,g,b),h=0,s=0,v=max/255,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)).data('sat',Math.round(s*100)).data('val',Math.round(v*100));
            $picker.find('.impulse-picker-cursor').css({left:Math.round(s*100)+'%',top:(100-Math.round(v*100))+'%'});
            $picker.find('.impulse-picker-hue .impulse-picker-thumb').css('left',((Math.round(h*360)/360)*100)+'%');
            applyStorePickerColor($picker);
        });

        $(document).on('click.storeColorPicker', function(e) {
            if (!$(e.target).closest('.impulse-store-picker, .impulse-store-right-content .impulse-color-swatch').length) {
                $('.impulse-store-picker').removeClass('open');
            }
        });
    })();

    function bindActionButtons() {
        
        $(document).on('click', '#settings-detail-content .btn-approve-rma', function() {
            var id = selectedItemId;
            actionAjax('instinctor_rma_action', { rma_id: id, action: 'approve' }, function() {
                updateListItemStatus(id, 'rma', 'approved');
            });
        });
        
        $(document).on('click', '#settings-detail-content .btn-reject-rma', function() {
            var id = selectedItemId;
            actionAjax('instinctor_rma_action', { rma_id: id, action: 'reject' }, function() {
                $('[data-rma-id="' + id + '"]').fadeOut();
                resetDetailPanel();
            });
        });

        $(document).on('click', '#settings-detail-content .btn-confirm-booking', function() {
            var id = selectedItemId;
            actionAjax('instinctor_booking_action', { booking_id: id, action: 'confirm' }, function() {
                updateListItemStatus(id, 'booking', 'confirmed');
            });
        });
        
        $(document).on('click', '#settings-detail-content .btn-cancel-booking', function() {
            var id = selectedItemId;
            if (!window.impulseConfirm('Cancel this booking?')) return;
            actionAjax('instinctor_booking_action', { booking_id: id, action: 'cancel' }, function() {
                $('[data-booking-id="' + id + '"]').fadeOut();
                resetDetailPanel();
            });
        });
    }
    
    function actionAjax(action, data, onSuccess) {
        data.action = action;
        data._wpnonce = window.Impulse.operationsNonce;
        $.post(ajaxurl, data, function(response) {
            if (response.success && onSuccess) {
                onSuccess(response);
            }
        });
    }
    
    function updateListItemStatus(id, type, status) {
        var $item = $('[data-' + type + '-id="' + id + '"]');
        $item.find('.impulse-status, [style*="background"]').first().css({
            'background': status === 'approved' || status === 'confirmed' ? '#2a2e33' : '#1a1d21',
            'color': status === 'approved' || status === 'confirmed' ? '#e0e0e0' : '#888'
        }).text(status.charAt(0).toUpperCase() + status.slice(1));
    }

    function loadOrderDetail(orderId) {
        
        $('#dashboard-detail-content').html('<div style="padding:40px 16px;text-align:center;color:#555">Loading...</div>');
        
        $.post(ajaxurl, {
            action: 'instinctor_get_order_detail',
            order_id: orderId,
            nonce: window.Impulse.adminNonce
        }, function(response) {
            if (!response.success) {
                $('#dashboard-detail-content').html('<div style="padding:16px;color:#999">Error loading order</div>');
                return;
            }
            var order = response.data;
            window._orderAddonLabels = {};
            renderOrderDetail(order);
        });
    }
    
    function renderOrderDetail(order) {
        if (typeof window.storeRightExpand === 'function') window.storeRightExpand();
        $('#order-detail-header').show().find('span').text(((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.order : 'Order') + ' Details');
        
        var html = '<div style="padding:8px 12px 16px">';

        html += '<div class="impulse-detail-section">';
        html += '<label style="font-size:11px;color:#aaa;display:block;margin-bottom:6px">Status</label>';
        html += '<div class="impulse-order-status-btns" data-order-id="' + order.id + '">';
        ['pending','processing','shipped','completed','cancelled','refunded','on-hold'].filter(function(s){ return !(s === 'shipped' && window.Impulse && (window.Impulse.storeType === 'memberships' || window.Impulse.storeType === 'services')); }).forEach(function(s) {
            var label = s === 'on-hold' ? 'On Hold' : s.charAt(0).toUpperCase() + s.slice(1);
            html += '<button type="button" class="impulse-order-status-btn' + (s === order.status ? ' active' : '') + '" data-status="' + s + '">' + label + '</button>';
        });
        html += '</div>';
        html += '<label style="display:flex;align-items:center;gap:6px;margin-top:8px;font-size:11px;color:#aaa;cursor:pointer">';
        html += '<input type="checkbox" id="order-send-email" checked> Send email notification';
        html += '</label>';
        html += '</div>';

        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer : 'Customer') + '</label>';
        if (order.customer_id) {
            html += '<div style="color:#e0e0e0;cursor:pointer;text-decoration:underline;text-decoration-color:#555" class="impulse-order-client-link" data-customer-id="' + order.customer_id + '">' + escapeHtml(order.customer_name || order.customer_email || ('View ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer : 'Client'))) + '</div>';
        } else {
            html += '<div style="color:#e0e0e0">' + escapeHtml(order.customer_name || 'Guest') + '</div>';
        }
        if (order.customer_email) html += '<div style="font-size:11px;color:#aaa">' + escapeHtml(order.customer_email) + '</div>';
        html += '</div>';

        if (order.items && order.items.length) {
            html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Items</label>';
            order.items.forEach(function(item) {
                html += '<div style="margin-bottom:6px">';
                var unitPrice = parseFloat(item.price || 0);
                var lineTotal = parseFloat(item.total || 0);
                var qty = parseInt(item.quantity) || 1;
                html += '<div style="display:flex;justify-content:space-between;font-size:11px;color:#ccc">';
                html += '<span>' + escapeHtml(item.name) + '</span>';
                html += '<span>' + order.currency + lineTotal.toFixed(2) + '</span>';
                html += '</div>';
                if (qty > 1) {
                    html += '<div style="font-size:10px;color:#888;margin-top:1px">' + order.currency + unitPrice.toFixed(2) + ' × ' + qty + '</div>';
                }
                
                var addons = item.addons || {};
                var addonKeys = Object.keys(addons);
                if (addonKeys.length > 0) {
                    var chips = addonKeys.map(function(name) {
                        var val   = addons[name];
                        var label = (val === '1' || val === 1) ? escapeHtml(name) : (escapeHtml(name) + ': ' + escapeHtml(String(val)));
                        return '<span style="display:inline-block;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;padding:1px 6px;font-size:10px;color:#999;margin:2px 2px 0 0">' + label + '</span>';
                    }).join('');
                    html += '<div style="margin-top:3px;line-height:1.6">' + chips + '</div>';
                }
                html += '</div>';
            });
            
            var subtotal = parseFloat(order.subtotal || 0);
            var discount = parseFloat(order.discount_total || 0);
            var shipping = parseFloat(order.shipping_total || 0);
            var tax      = parseFloat(order.tax_total || 0);
            var total    = parseFloat(order.total || 0);
            html += '<div style="margin-top:8px;padding-top:6px;border-top:1px solid #2a2e33">';
            html += '<div style="display:flex;justify-content:space-between;font-size:11px;color:#aaa;margin-bottom:3px"><span>Subtotal</span><span>' + order.currency + subtotal.toFixed(2) + '</span></div>';
            if (discount > 0) {
                html += '<div style="display:flex;justify-content:space-between;font-size:11px;color:#aaa;margin-bottom:3px"><span>Discount</span><span>−' + order.currency + discount.toFixed(2) + '</span></div>';
            }
            if (shipping > 0) {
                html += '<div style="display:flex;justify-content:space-between;font-size:11px;color:#aaa;margin-bottom:3px"><span>Shipping</span><span>' + order.currency + shipping.toFixed(2) + '</span></div>';
            }
            if (tax > 0) {
                html += '<div style="display:flex;justify-content:space-between;font-size:11px;color:#aaa;margin-bottom:3px"><span>Tax</span><span>' + order.currency + tax.toFixed(2) + '</span></div>';
            }
            html += '<div style="display:flex;justify-content:space-between;font-size:13px;font-weight:600;color:#e0e0e0;margin-top:4px"><span>Total</span><span>' + order.currency + total.toFixed(2) + '</span></div>';
            html += '</div>';
            html += '</div>';
        }

        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Date</label>';
        html += '<div style="font-size:11px;color:#ccc">' + order.date + '</div></div>';

        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:6px">Tracking</label>';
        html += '<div style="display:flex;gap:4px;margin-bottom:8px">';
        
        var carriers = [{val:'other',label:'Carrier'},{val:'usps',label:'USPS'},{val:'ups',label:'UPS'},{val:'fedex',label:'FedEx'},{val:'dhl',label:'DHL'},{val:'amazon',label:'Amazon'},{val:'ontrac',label:'OnTrac'},{val:'lasership',label:'LaserShip'},{val:'canada_post',label:'Canada Post'},{val:'royal_mail',label:'Royal Mail'}];
        var currentCarrier = order.tracking_carrier || 'other';
        var currentLabel = 'Carrier';
        carriers.forEach(function(c) { if (c.val === currentCarrier) currentLabel = c.label; });
        html += '<div class="impulse-custom-select" id="order-tracking-carrier-wrap" style="position:relative;flex-shrink:0">';
        html += '<button type="button" class="impulse-custom-select-btn" id="order-tracking-carrier-btn" data-value="' + currentCarrier + '">' + escapeHtml(currentLabel) + ' <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-left:4px;vertical-align:middle"><path d="M6 9l6 6 6-6"/></svg></button>';
        html += '<div class="impulse-custom-select-list" id="order-tracking-carrier-list" style="display:none">';
        carriers.forEach(function(c) {
            html += '<div class="impulse-custom-select-option' + (c.val === currentCarrier ? ' active' : '') + '" data-value="' + c.val + '">' + escapeHtml(c.label) + '</div>';
        });
        html += '</div></div>';
        html += '<input type="text" id="order-tracking-number" value="' + escapeHtml(order.tracking_number || '') + '" placeholder="Tracking number..." style="flex:1">';
        html += '</div>';
        html += '<button type="button" class="impulse-btn-sm" id="btn-save-tracking" data-order-id="' + order.id + '">Save Tracking</button>';
        html += '</div>';

        html += '<div class="impulse-detail-section" style="border-top:1px solid #2a2e33;padding-top:10px;margin-top:4px">';
        html += '<button type="button" class="impulse-btn-sm" id="btn-delete-order" data-order-id="' + order.id + '">Delete Order</button>';
        html += '</div>';
        
        html += '</div>';
        $('#dashboard-detail-content').html(html);
    }

    

    var STATUS_LABELS = ['pending','processing','shipped','completed','cancelled','refunded','on-hold'];
    var STATUS_NAMES  = { pending:'Pending', processing:'Processing', shipped:'Shipped', completed:'Completed', cancelled:'Cancelled', refunded:'Refunded', 'on-hold':'On Hold' };

    function closeStatusModal() {
        $('#order-status-modal').remove();
        $(document).off('mousedown.osm keydown.osm');
    }

    function openStatusModal($badge, orderId, currentStatus) {
        closeStatusModal();

        var btns = STATUS_LABELS.map(function(s) {
            return '<button type="button" class="osm-btn osm-' + s + (s === currentStatus ? ' current' : '') + '" data-status="' + s + '">'
                 + STATUS_NAMES[s] + '</button>';
        }).join('');

        var $modal = $('<div id="order-status-modal">' + btns + '</div>');
        $('body').append($modal);

        var rect = $badge[0].getBoundingClientRect();
        var mw   = $modal.outerWidth();
        var mh   = $modal.outerHeight();
        var top  = rect.top + rect.height / 2 - mh / 2;
        var left = rect.left - mw - 6;
        top  = Math.max(8, Math.min(top, window.innerHeight - mh - 8));
        if (left < 8) left = rect.right + 6;
        $modal.css({ top: top + 'px', left: left + 'px' });

        $(document).on('mousedown.osm', function(e) {
            if (!$(e.target).closest('#order-status-modal').length) closeStatusModal();
        });

        $(document).on('keydown.osm', function(e) {
            if (e.key === 'Escape') closeStatusModal();
        });

        $modal.on('click', '.osm-btn', function() {
            var newStatus = $(this).data('status');
            closeStatusModal();
            if (newStatus === currentStatus) return;

            $badge.removeClass().addClass('impulse-status impulse-status-' + newStatus)
                  .text(STATUS_NAMES[newStatus]);
            $badge.closest('[data-order-id]').attr('data-status', newStatus);
            filterOrders();

            $.post(ajaxurl, {
                action:     'instinctor_update_order_status',
                nonce:      window.Impulse.adminNonce,
                order_id:   orderId,
                status:     newStatus,
                send_email: 0
            }, function(res) {
                if (!res.success) {
                    showToast((res.data && res.data.message) ? res.data.message : 'Error updating status', 'error');
                    $badge.removeClass().addClass('impulse-status impulse-status-' + currentStatus)
                          .text(STATUS_NAMES[currentStatus]);
                    $badge.closest('[data-order-id]').attr('data-status', currentStatus);
                    filterOrders();
                }
            }).fail(function() { showToast('Request failed', 'error'); });
        });
    }

    $(document).on('click', '#dashboard-orders-list .impulse-status', function() {
        var $badge  = $(this);
        var $row    = $badge.closest('[data-order-id]');
        openStatusModal($badge, $row.data('order-id'), $row.attr('data-status'));
    });

    $(document).on('click', '.impulse-order-status-btn', function() {
        var $btn = $(this);
        var $group = $btn.closest('.impulse-order-status-btns');
        var orderId = $group.data('order-id');
        var newStatus = $btn.data('status');
        var sendEmail = $('#order-send-email').is(':checked');
        
        if ($btn.hasClass('active')) return; 
        
        $group.find('.impulse-order-status-btn').prop('disabled', true);
        
        $.post(ajaxurl, {
            action: 'instinctor_update_order_status',
            order_id: orderId,
            status: newStatus,
            send_email: sendEmail ? 1 : 0,
            nonce: window.Impulse.adminNonce
        }, function(response) {
            $group.find('.impulse-order-status-btn').prop('disabled', false);
            if (response.success) {
                $group.find('.impulse-order-status-btn').removeClass('active');
                $btn.addClass('active');
                var emailMsg = sendEmail ? (response.data.email_sent ? ' · email sent' : ' · email failed') : '';
                showToast('Status updated' + emailMsg);
                
                var $item = $('#dashboard-orders-list .impulse-list-item[data-order-id="' + orderId + '"]');
                $item.attr('data-status', newStatus);
                $item.find('.impulse-status').removeClass().addClass('impulse-status impulse-status-' + newStatus).text(newStatus === 'on-hold' ? 'On Hold' : newStatus.charAt(0).toUpperCase() + newStatus.slice(1));
                filterOrders();
            } else {
                showToast(response.data?.message || 'Error updating status', 'error');
            }
        }).fail(function() {
            $group.find('.impulse-order-status-btn').prop('disabled', false);
            showToast('Request failed', 'error');
        });
    });

    $(document).on('click', '#btn-delete-order', function() {
        var orderId = $(this).data('order-id');
        if (!window.impulseConfirm('Delete this ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.order.toLowerCase() : 'order') + '? This cannot be undone.')) return;
        var $btn = $(this).prop('disabled', true).text('Deleting…');
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_delete_order',
            nonce: window.Impulse.adminNonce,
            order_id: orderId
        }, function(res) {
            if (res.success) {
                $('#dashboard-detail-content, #order-detail-header').html('').hide();
                if (typeof window.loadOrders === 'function') window.loadOrders();
                showToast('Order deleted');
            } else {
                $btn.prop('disabled', false).text('Delete Order');
                showToast('Failed to delete order', 'error');
            }
        });
    });

    $(document).on('click', '#btn-delete-client', function() {
        var customerId = $(this).data('customer-id');
        if (!window.impulseConfirm('Delete this ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer.toLowerCase() : 'client') + '? Their ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.order.toLowerCase() : 'order') + ' history will not be deleted.')) return;
        var $btn = $(this).prop('disabled', true).text('Deleting…');
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_delete_client',
            nonce: window.Impulse.adminNonce,
            customer_id: customerId
        }, function(res) {
            if (res.success) {
                $('#customer-detail-content').html('');
                $('#clients-right-header').hide();
                if (typeof loadClientsCenter === 'function') loadClientsCenter();
                showToast('Client deleted');
            } else {
                $btn.prop('disabled', false).text('Delete ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer : 'Client'));
                showToast('Failed to delete client', 'error');
            }
        });
    });

    $(document).on('click', '#btn-save-tracking', function() {
        var orderId = $(this).data('order-id');
        var trackingNumber = $('#order-tracking-number').val();
        var carrier = $('#order-tracking-carrier-btn').data('value');
        var $btn = $(this);
        
        $btn.prop('disabled', true).text('Saving...');
        
        $.post(ajaxurl, {
            action: 'instinctor_save_tracking',
            order_id: orderId,
            tracking_number: trackingNumber,
            tracking_url: '',
            carrier: carrier,
            nonce: window.Impulse.adminNonce
        }, function(response) {
            $btn.prop('disabled', false).text('Save Tracking');
            if (response.success) {
                showToast('Tracking info saved');
            } else {
                showToast(response.data?.message || 'Error saving tracking', 'error');
            }
        }).fail(function() {
            $btn.prop('disabled', false).text('Save Tracking');
            showToast('Request failed', 'error');
        });
    });

    var _carrierTimer = null;
    function closeCarrierDropdown() {
        $('#order-tracking-carrier-list').hide();
        if (_carrierTimer) { clearTimeout(_carrierTimer); _carrierTimer = null; }
    }
    $(document).on('click', '#order-tracking-carrier-btn', function(e) {
        e.stopPropagation();
        var $list = $('#order-tracking-carrier-list');
        var wasOpen = $list.is(':visible');
        $list.toggle();
        if (_carrierTimer) clearTimeout(_carrierTimer);
        if (!wasOpen) {
            _carrierTimer = setTimeout(closeCarrierDropdown, 3000);
        }
    });
    $(document).on('click', '.impulse-custom-select-option', function() {
        var val = $(this).data('value');
        var label = $(this).text();
        $('#order-tracking-carrier-btn').data('value', val).contents().first()[0].textContent = label + ' ';
        $(this).addClass('active').siblings().removeClass('active');
        closeCarrierDropdown();
    });
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#order-tracking-carrier-wrap').length) {
            closeCarrierDropdown();
        }
    });
    
    $(document).on('click', '.impulse-store-nav-btn, .impulse-workspace-btn, #orders-mode-orders, #orders-mode-clients, #orders-mode-returns', function() {
        closeCarrierDropdown();
    });

    var clientsState = {
        initialized: false,
        segment: 'all',
        search: '',
        page: 1,
        loading: false,
        hasMore: false,
        selectedId: null
    };

    function initClientsWorkspace() {
        if (clientsState.initialized) return;
        clientsState.initialized = true;

        var _searchTimer = null;
        $(document).on('input', '#clients-search', function() {
            clearTimeout(_searchTimer);
            var q = $(this).val().trim();
            _searchTimer = setTimeout(function() {
                clientsState.search = q;
                clientsState.page = 1;
                loadClientsCenter();
            }, 300);
        });

        $(document).on('change', '[name="clients_nav"]', function() {
            var $label = $(this).closest('.impulse-filter-option');
            var seg = $label.data('segment') || 'all';
            $('.impulse-filter-option[data-clients-mode]').removeClass('active');
            $label.addClass('active');
            clientsState.segment = seg;
            clientsState.page = 1;
            clientsState.search = '';
            $('#clients-search').val('');
            clearClientsRight();
            loadClientsCenter();
        });

        $(document).on('scroll.clientscroll', '#clients-center-list', function() {
            if (clientsState.loading || !clientsState.hasMore) return;
            var $el = $(this);
            if ($el.scrollTop() + $el.innerHeight() >= $el[0].scrollHeight - 150) {
                clientsState.page++;
                loadClientsCenter(true);
            }
        });

        loadClientsCenter();
    }

    function clearClientsRight() {
        clientsState.selectedId = null;
        $('#clients-center-list .impulse-list-item').removeClass('active');
        $('#clients-right-header').hide();
        $('#customer-detail-content').html('');
    }

    function loadClientsCenter(append) {
        if (clientsState.loading) return;
        clientsState.loading = true;

        var $list = $('#clients-center-list');
        if (!append) $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Loading…</li>');

        $.post(window.Impulse.ajaxUrl, {
            action:  'instinctor_get_customers',
            nonce:   window.Impulse.adminNonce,
            segment: clientsState.segment,
            search:  clientsState.search,
            page:    clientsState.page
        }, function(res) {
            clientsState.loading = false;
            if (!res.success) { $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Error</li>'); return; }
            var data = res.data;
            clientsState.hasMore = data.has_more;
            $('#clients-toolbar-count').text(data.total ? '(' + data.total + ')' : '');
            
            if (data.segment_counts) {
                var sc = data.segment_counts;
                if (data.mode === 'memberships') {
                    $('#clients-count-all').text(sc.all || 0);
                    $('#clients-count-active').text(sc.active || 0);
                    $('#clients-count-canceled').text(sc.canceled || 0);
                    $('#clients-count-new').text(sc.new_30d || 0);
                    $('#cstat-total').text(sc.all || 0);
                    $('#cstat-active').text(sc.active || 0);
                    $('#cstat-new').text(sc.new_30d || 0);
                    $('#cstat-canceled').text(sc.canceled || 0);
                } else {
                    $('#clients-count-all').text(sc.all || 0);
                    $('#clients-count-repeat').text(sc.repeat || 0);
                    $('#clients-count-high_value').text(sc.high_value || 0);
                    $('#clients-count-inactive').text(sc.inactive || 0);
                    $('#cstat-total').text(sc.all || 0);
                    $('#cstat-repeat').text(sc.repeat || 0);
                    $('#cstat-new').text(sc.new_30d || 0);
                    $('#cstat-inactive').text(sc.inactive || 0);
                }
            }
            if (!append) {
                if (!data.customers.length) {
                    $list.html('<li class="impulse-empty"><div class="impulse-empty-title">No ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customers.toLowerCase() : 'clients') + '</div></li>');
                    return;
                }
                $list.html('');
            }
            data.customers.forEach(function(c) { $list.append(buildClientRow(c)); });
            if (data.has_more) $list.append('<li class="impulse-load-more-sentinel" style="height:1px"></li>');
            else $list.find('.impulse-load-more-sentinel').remove();
        }).fail(function() {
            clientsState.loading = false;
            $list.html('<li style="padding:20px;text-align:center;color:#555;font-size:11px">Failed</li>');
        });
    }

    function buildClientRow(c) {
        var isSelected = clientsState.selectedId === c.id ? ' active' : '';
        var html = '<li class="impulse-list-item' + isSelected + '" data-customer-id="' + c.id + '">';
        html += '<span class="impulse-list-client-name">' + escapeHtml(c.name || c.email) + '</span>';
        if (c.status) {

            var dim = c.status !== 'active' ? ';opacity:0.5' : '';
            html += '<span class="impulse-list-client-orders" style="text-transform:none' + dim + '">' + escapeHtml(c.status_label || c.status) + '</span>';
            if (c.member_since) html += '<span class="impulse-list-client-date">' + escapeHtml(c.member_since) + '</span>';
            html += '<span class="impulse-list-client-total">' + escapeHtml(c.price_label || '') + '</span>';
        } else {
            var total = parseFloat(c.total_spent);
            html += '<span class="impulse-list-client-orders">' + c.order_count + ' ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.order.toLowerCase() : 'order') + (c.order_count !== 1 ? 's' : '') + '</span>';
            if (c.last_order_date) html += '<span class="impulse-list-client-date">' + escapeHtml(c.last_order_date) + '</span>';
            html += '<span class="impulse-list-client-total">' + (total > 0 ? c.currency + total.toFixed(2) : '') + '</span>';
        }
        html += '</li>';
        return html;
    }

    
    
    function renderSalonCRM(c) {
        var s = c.salon, esc = escapeHtml;
        if (s && s.locked) {
            return '<div class="impulse-detail-section imp-salon"><div style="text-align:center;padding:20px 12px;background:#1a1d21;border:1px solid #2a2e33;border-radius:10px">'
                + '<svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="#8a9099" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:8px"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>'
                + '<div style="font-size:12px;font-weight:600;color:#e0e0e0;margin-bottom:4px">Client profiles are a Pro feature</div>'
                + '<div style="font-size:11px;color:#888;line-height:1.5;max-width:250px;margin:0 auto">Visit history, before &amp; after photos, and color formulas unlock with Instinctor Pro.</div>'
                + '</div></div>';
        }
        var inp = 'height:26px;padding:0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;box-sizing:border-box';
        var h = '<div class="impulse-detail-section imp-salon" data-cid="' + c.id + '">';

        h += '<div class="imp-salon-soft">';
        h += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:5px"><span style="font-size:11px;color:#aaa">Client details</span><button type="button" class="impulse-btn-sm imp-salon-soft-edit" style="height:22px;padding:0 8px;font-size:10px">Edit</button></div>';
        h += '<div class="imp-salon-soft-view">';
        if (s.tags && s.tags.length) { h += '<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px">'; s.tags.forEach(function(t){ h += '<span style="font-size:10px;color:#e0e0e0;background:#2a2e33;border:1px solid #3a3f44;border-radius:10px;padding:1px 8px">' + esc(t) + '</span>'; }); h += '</div>'; }
        var mv = []; if (s.birthday) mv.push('Birthday ' + esc(s.birthday)); if (s.allergies) mv.push('Allergies: ' + esc(s.allergies));
        if (mv.length) h += '<div style="font-size:11px;color:#888">' + mv.join('   ·   ') + '</div>';
        if (!(s.tags && s.tags.length) && !mv.length) h += '<div style="font-size:11px;color:#555">No tags or details yet.</div>';
        h += '</div>';
        h += '<div class="imp-salon-soft-form" style="display:none;margin-top:6px">';
        h += '<input type="text" class="imp-soft-tags" placeholder="Tags (comma separated)" value="' + esc((s.tags||[]).join(', ')) + '" style="width:100%;margin-bottom:4px;' + inp + '">';
        h += '<input type="date" class="imp-soft-birthday" value="' + esc(s.birthday||'') + '" style="width:100%;margin-bottom:4px;' + inp + '">';
        h += '<input type="text" class="imp-soft-allergies" placeholder="Allergies / sensitivities" value="' + esc(s.allergies||'') + '" style="width:100%;margin-bottom:5px;' + inp + '">';
        h += '<div style="display:flex;justify-content:flex-end;gap:5px"><button type="button" class="impulse-btn-sm imp-salon-soft-cancel" style="height:24px;padding:0 10px;font-size:10px">Cancel</button><button type="button" class="impulse-btn-sm imp-salon-soft-save" style="height:24px;padding:0 12px;font-size:10px">Save</button></div>';
        h += '</div></div>';

        var tabs = [['visits','Visits',(s.visits||[]).length],['photos','Before / after',(s.photos||[]).length],['formulas','Formulas',(s.formulas||[]).length]];
        h += '<div style="display:flex;gap:2px;margin:10px 0 8px;border-bottom:1px solid #3a3f44">';
        tabs.forEach(function(t,i){ h += '<button type="button" class="imp-salon-tab" data-salontab="' + t[0] + '" style="height:26px;padding:0 8px;font-size:10px;background:none;border:none;border-bottom:2px solid ' + (i===0?'#e0e0e0':'transparent') + ';color:' + (i===0?'#e0e0e0':'#888') + ';cursor:pointer">' + t[1] + (t[2]?' (' + t[2] + ')':'') + '</button>'; });
        h += '</div>';

        h += '<div class="imp-salon-pane" data-pane="visits">';
        if (s.visits && s.visits.length) { s.visits.forEach(function(v){ var d = v.dt ? String(v.dt).split(' ')[0] : '';
            h += '<div style="display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid #23262b"><span style="font-size:11px;color:#888;flex-shrink:0;width:74px">' + esc(d) + '</span><span style="flex:1;min-width:0;font-size:11px;color:#e0e0e0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + esc(v.label||'Appointment') + '</span><span style="font-size:10px;color:#555;text-transform:capitalize">' + esc(v.status||'') + '</span></div>'; });
        } else { h += '<div style="font-size:11px;color:#555;padding:8px 0">No appointments yet.</div>'; }
        h += '</div>';

        h += '<div class="imp-salon-pane" data-pane="photos" style="display:none">';
        h += '<button type="button" class="impulse-btn-sm imp-photo-add" style="height:24px;padding:0 10px;font-size:10px;margin-bottom:8px">+ Add before / after</button>';
        h += '<div class="imp-photo-form" style="display:none;margin-bottom:8px;padding:8px;background:#1a1d21;border:1px solid #3a3f44;border-radius:4px">';
        h += '<div style="display:flex;gap:6px;margin-bottom:6px">';
        h += '<div style="flex:1"><div style="font-size:10px;color:#888;margin-bottom:3px">Before</div><div class="imp-photo-slot" data-slot="before" style="aspect-ratio:1;background:#2a2e33;border:1px dashed #3a3f44;border-radius:4px;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:10px;color:#666;overflow:hidden">Choose</div></div>';
        h += '<div style="flex:1"><div style="font-size:10px;color:#888;margin-bottom:3px">After</div><div class="imp-photo-slot" data-slot="after" style="aspect-ratio:1;background:#2a2e33;border:1px dashed #3a3f44;border-radius:4px;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:10px;color:#666;overflow:hidden">Choose</div></div>';
        h += '</div>';
        h += '<input type="text" class="imp-photo-service" placeholder="Service (e.g. Balayage)" style="width:100%;margin-bottom:4px;' + inp + '">';
        h += '<input type="date" class="imp-photo-date" style="width:100%;margin-bottom:5px;' + inp + '">';
        h += '<div style="display:flex;justify-content:flex-end;gap:5px"><button type="button" class="impulse-btn-sm imp-photo-cancel" style="height:24px;padding:0 10px;font-size:10px">Cancel</button><button type="button" class="impulse-btn-sm imp-photo-save" style="height:24px;padding:0 12px;font-size:10px">Save</button></div></div>';
        if (s.photos && s.photos.length) { s.photos.forEach(function(p){
            h += '<div style="margin-bottom:8px;padding:6px;background:#1a1d21;border:1px solid #23262b;border-radius:4px"><div style="display:flex;gap:4px;margin-bottom:4px">';
            h += '<div style="flex:1;position:relative">' + (p.before_url?'<img src="'+esc(p.before_thumb||p.before_url)+'" style="width:100%;aspect-ratio:1;object-fit:cover;border-radius:3px;display:block">':'<div style="aspect-ratio:1;background:#2a2e33;border-radius:3px"></div>') + '<span style="position:absolute;top:3px;left:3px;font-size:9px;background:rgba(0,0,0,.6);color:#fff;padding:0 4px;border-radius:2px">Before</span></div>';
            h += '<div style="flex:1;position:relative">' + (p.after_url?'<img src="'+esc(p.after_thumb||p.after_url)+'" style="width:100%;aspect-ratio:1;object-fit:cover;border-radius:3px;display:block">':'<div style="aspect-ratio:1;background:#2a2e33;border-radius:3px"></div>') + '<span style="position:absolute;top:3px;left:3px;font-size:9px;background:rgba(0,0,0,.6);color:#fff;padding:0 4px;border-radius:2px">After</span></div></div>';
            var pm = []; if (p.service) pm.push(esc(p.service)); if (p.taken_at) pm.push(esc(p.taken_at));
            h += '<div style="display:flex;align-items:center;justify-content:space-between"><span style="font-size:10px;color:#888">' + pm.join('   ·   ') + '</span><button type="button" class="imp-photo-del" data-id="' + p.id + '" style="background:none;border:none;color:#666;font-size:10px;cursor:pointer">Delete</button></div></div>';
        }); } else { h += '<div style="font-size:11px;color:#555;padding:4px 0">No before/after yet.</div>'; }
        h += '</div>';

        h += '<div class="imp-salon-pane" data-pane="formulas" style="display:none">';
        h += '<button type="button" class="impulse-btn-sm imp-formula-add" style="height:24px;padding:0 10px;font-size:10px;margin-bottom:8px">+ Add formula</button>';
        h += '<div class="imp-formula-form" style="display:none;margin-bottom:8px;padding:8px;background:#1a1d21;border:1px solid #3a3f44;border-radius:4px">';
        h += '<input type="hidden" class="imp-formula-id" value="">';
        h += '<input type="text" class="imp-formula-title" placeholder="Title (e.g. Full head balayage)" style="width:100%;margin-bottom:4px;' + inp + '">';
        h += '<textarea class="imp-formula-body" placeholder="Formula / recipe…" rows="3" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;font-family:inherit;padding:6px 8px;box-sizing:border-box;resize:vertical;margin-bottom:4px"></textarea>';
        h += '<div style="display:flex;gap:4px;margin-bottom:4px"><input type="text" class="imp-formula-brand" placeholder="Brand" style="flex:1;min-width:0;' + inp + '"><input type="date" class="imp-formula-date" style="flex:1;min-width:0;' + inp + '"></div>';
        h += '<div style="display:flex;justify-content:flex-end;gap:5px"><button type="button" class="impulse-btn-sm imp-formula-cancel" style="height:24px;padding:0 10px;font-size:10px">Cancel</button><button type="button" class="impulse-btn-sm imp-formula-savebtn" style="height:24px;padding:0 12px;font-size:10px">Save</button></div></div>';
        if (s.formulas && s.formulas.length) { s.formulas.forEach(function(f){
            h += '<div class="imp-formula-card" data-id="' + f.id + '" data-title="'+esc(f.title||'')+'" data-brand="'+esc(f.brand||'')+'" data-service="'+esc(f.service||'')+'" data-used="'+esc(f.used_at||'')+'" style="margin-bottom:6px;padding:7px 8px;background:#1a1d21;border:1px solid #23262b;border-radius:4px">';
            h += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:2px"><span style="font-size:11px;font-weight:600;color:#e0e0e0">' + esc(f.title||'Formula') + '</span><span style="display:flex;gap:6px"><button type="button" class="imp-formula-edit" style="background:none;border:none;color:#888;font-size:10px;cursor:pointer">Edit</button><button type="button" class="imp-formula-del" style="background:none;border:none;color:#666;font-size:10px;cursor:pointer">Delete</button></span></div>';
            if (f.formula) h += '<div class="imp-formula-text" style="font-size:11px;color:#aaa;white-space:pre-wrap;line-height:1.5">' + esc(f.formula) + '</div>';
            var fm = []; if (f.brand) fm.push(esc(f.brand)); if (f.used_at) fm.push(esc(f.used_at));
            if (fm.length) h += '<div style="font-size:10px;color:#555;margin-top:3px">' + fm.join('   ·   ') + '</div>';
            h += '</div>';
        }); } else { h += '<div style="font-size:11px;color:#555;padding:4px 0">No formulas yet.</div>'; }
        h += '</div>';

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

    if (!window.__salonCrmBound) {
        window.__salonCrmBound = true;
        var _salonPost = function(action, data, cb){ data.action = action; data.nonce = window.Impulse.adminNonce; $.post(window.Impulse.ajaxUrl, data, cb); };
        var _salonCid = function(el){ return $(el).closest('.imp-salon').data('cid'); };
        $(document).on('click', '.imp-salon-tab', function(){
            var pane = $(this).data('salontab'), $root = $(this).closest('.imp-salon');
            $root.find('.imp-salon-tab').css({'border-bottom-color':'transparent','color':'#888'});
            $(this).css({'border-bottom-color':'#e0e0e0','color':'#e0e0e0'});
            $root.find('.imp-salon-pane').hide();
            $root.find('.imp-salon-pane[data-pane="'+pane+'"]').show();
        });
        $(document).on('click', '.imp-salon-soft-edit', function(){ var $s = $(this).closest('.imp-salon-soft'); $s.find('.imp-salon-soft-view').hide(); $s.find('.imp-salon-soft-form').show(); });
        $(document).on('click', '.imp-salon-soft-cancel', function(){ var $s = $(this).closest('.imp-salon-soft'); $s.find('.imp-salon-soft-form').hide(); $s.find('.imp-salon-soft-view').show(); });
        $(document).on('click', '.imp-salon-soft-save', function(){ var $s = $(this).closest('.imp-salon-soft'), c = _salonCid(this);
            _salonPost('instinctor_client_meta_save', { customer_id:c, tags:$s.find('.imp-soft-tags').val(), birthday:$s.find('.imp-soft-birthday').val(), allergies:$s.find('.imp-soft-allergies').val() }, function(r){ if(r && r.success) loadCustomerDetail(c); }); });
        $(document).on('click', '.imp-photo-add', function(){ $(this).siblings('.imp-photo-form').show(); $(this).hide(); });
        $(document).on('click', '.imp-photo-cancel', function(){ var $f = $(this).closest('.imp-photo-form'); $f.hide(); $f.siblings('.imp-photo-add').show(); });
        $(document).on('click', '.imp-photo-slot', function(){ var slot = this; if (typeof openImglibPicker !== 'function') return;
            openImglibPicker({ label:'Select photo', simple:true }, function(att){ var url = att && (att.url||att.full_url||att.src); if(!url) return;
                $(slot).attr('data-url', url).css('border-style','solid').html('<img src="'+url+'" style="width:100%;height:100%;object-fit:cover;border-radius:3px">'); }); });
        $(document).on('click', '.imp-photo-save', function(){ var $f = $(this).closest('.imp-photo-form'), c = _salonCid(this);
            var before = $f.find('.imp-photo-slot[data-slot="before"]').attr('data-url')||'', after = $f.find('.imp-photo-slot[data-slot="after"]').attr('data-url')||'';
            if(!before && !after) return;
            _salonPost('instinctor_client_photo_add', { customer_id:c, before_url:before, after_url:after, service:$f.find('.imp-photo-service').val(), taken_at:$f.find('.imp-photo-date').val() }, function(r){ if(r && r.success) loadCustomerDetail(c); }); });
        $(document).on('click', '.imp-photo-del', function(){ var id = $(this).data('id'), c = _salonCid(this);
            _salonPost('instinctor_client_photo_delete', { customer_id:c, photo_id:id }, function(r){ if(r && r.success) loadCustomerDetail(c); }); });
        $(document).on('click', '.imp-formula-add', function(){ var $f = $(this).siblings('.imp-formula-form'); $f.find('.imp-formula-id').val(''); $f.find('.imp-formula-title,.imp-formula-body,.imp-formula-brand,.imp-formula-date').val(''); $f.show(); $(this).hide(); });
        $(document).on('click', '.imp-formula-cancel', function(){ var $f = $(this).closest('.imp-formula-form'); $f.hide(); $f.siblings('.imp-formula-add').show(); });
        $(document).on('click', '.imp-formula-edit', function(){ var $card = $(this).closest('.imp-formula-card'), $f = $card.closest('.imp-salon-pane').find('.imp-formula-form');
            $f.find('.imp-formula-id').val($card.data('id')); $f.find('.imp-formula-title').val($card.data('title')); $f.find('.imp-formula-body').val($card.find('.imp-formula-text').text()); $f.find('.imp-formula-brand').val($card.data('brand')); $f.find('.imp-formula-date').val($card.data('used'));
            $f.show(); $f.siblings('.imp-formula-add').hide(); });
        $(document).on('click', '.imp-formula-savebtn', function(){ var $f = $(this).closest('.imp-formula-form'), c = _salonCid(this), title = $f.find('.imp-formula-title').val();
            if(!String(title).trim()){ $f.find('.imp-formula-title').focus(); return; }
            _salonPost('instinctor_client_formula_save', { customer_id:c, formula_id:$f.find('.imp-formula-id').val()||0, title:title, formula:$f.find('.imp-formula-body').val(), brand:$f.find('.imp-formula-brand').val(), used_at:$f.find('.imp-formula-date').val() }, function(r){ if(r && r.success) loadCustomerDetail(c); }); });
        $(document).on('click', '.imp-formula-del', function(){ var id = $(this).closest('.imp-formula-card').data('id'), c = _salonCid(this);
            _salonPost('instinctor_client_formula_delete', { customer_id:c, formula_id:id }, function(r){ if(r && r.success) loadCustomerDetail(c); }); });
    }

    $(document).on('click', '#clients-center-list .impulse-list-item[data-customer-id]', function() {
        clientsState.selectedId = $(this).data('customer-id');
        $('#clients-center-list .impulse-list-item').removeClass('active');
        $(this).addClass('active');
        loadCustomerDetail(clientsState.selectedId);
    });

    function loadCustomerDetail(customerId) {
        if (typeof window.storeRightExpand === 'function') window.storeRightExpand();
        $('#order-detail-header').hide();
        $('#clients-right-header').show();
        $('#clients-right-title').text(((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer : 'Client') + ' Details');
        $('#dashboard-detail-content').html('');

        var $content = $('#customer-detail-content');
        $content.html('<div style="padding:16px;text-align:center;color:#555;font-size:11px;margin-top:40px">Loading…</div>');

        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_get_customer_detail',
            nonce: window.Impulse.adminNonce,
            customer_id: customerId
        }, function(response) {
            if (!response.success) { $content.html('<div style="padding:16px;color:#555;font-size:11px">' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer : 'Client') + ' not found.</div>'); return; }
            var c = response.data;
            var currency = c.currency || '$';
            var totalSpent = parseFloat(c.total_spent);
            var html = '<div style="padding:8px 12px 16px">';

            html += '<div class="impulse-detail-section">';
            html += '<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px">';
            html += '<div style="min-width:0">';
            html += '<div style="font-weight:600;color:#e0e0e0;font-size:12px">' + escapeHtml(c.name || c.email) + '</div>';
            html += '<a href="mailto:' + escapeHtml(c.email) + '" style="color:#888;font-size:11px;text-decoration:none">' + escapeHtml(c.email) + '</a>';
            if (c.phone) html += '<div style="color:#666;font-size:11px;margin-top:1px">' + escapeHtml(c.phone) + '</div>';
            if (c.address) html += '<div style="color:#555;font-size:11px;margin-top:2px">' + escapeHtml(c.address) + '</div>';
            html += '</div>';
            html += '<button type="button" class="impulse-btn-sm" id="member-edit-toggle" style="height:22px;padding:0 8px;font-size:10px;flex-shrink:0">Edit</button>';
            html += '</div>';

            
            var canBill = !!(c.subscription && c.subscription.status === 'active' && c.subscription.billable);
            html += '<div id="member-edit-form" style="display:none;margin-top:8px;padding-top:8px;border-top:1px solid #3a3f44">';
            html += '<div style="display:flex;gap:5px;margin-bottom:5px">';
            html += '<input type="text" id="member-edit-first" placeholder="First name" value="' + escapeHtml(c.first_name || '') + '" style="flex:1;min-width:0;height:26px;padding:0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;box-sizing:border-box">';
            html += '<input type="text" id="member-edit-last" placeholder="Last name" value="' + escapeHtml(c.last_name || '') + '" style="flex:1;min-width:0;height:26px;padding:0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;box-sizing:border-box">';
            html += '</div>';
            if (canBill) {
                html += '<div style="display:flex;align-items:center;gap:6px;margin-bottom:3px">';
                html += '<span style="font-size:11px;color:#888;flex-shrink:0">' + escapeHtml(currency) + ' / mo</span>';
                html += '<input type="text" inputmode="decimal" id="member-edit-amount" placeholder="Amount" value="' + escapeHtml(String(c.subscription.price || '')) + '" style="flex:1;min-width:0;height:26px;padding:0 8px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;box-sizing:border-box">';
                html += '</div>';
                html += '<div style="font-size:10px;color:#999;margin-bottom:6px">This changes the live recurring charge for every future payment.</div>';
            }
            html += '<div style="display:flex;justify-content:flex-end;gap:5px">';
            html += '<button type="button" class="impulse-btn-sm" id="member-edit-cancel" style="height:24px;padding:0 10px;font-size:10px">Cancel</button>';
            html += '<button type="button" class="impulse-btn-sm" id="member-edit-save" data-customer-id="' + c.id + '" style="height:24px;padding:0 12px;font-size:10px">Save</button>';
            html += '</div>';
            html += '</div>';
            html += '</div>';

            if (c.subscription) {

                var sub = c.subscription;
                html += '<div class="impulse-detail-section">';
                html += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:3px">';
                html += '<span style="font-size:12px;font-weight:600;color:#e0e0e0">' + escapeHtml(sub.plan || 'Membership') + '</span>';
                html += '<span style="font-size:11px;color:' + (sub.status === 'active' ? '#e0e0e0' : '#888') + '">' + escapeHtml(sub.status_label || sub.status) + '</span>';
                html += '</div>';
                var line2 = [];
                if (sub.price_label) line2.push(sub.price_label);
                if (sub.since) line2.push('Since ' + sub.since);
                if (sub.status === 'active' && sub.renews) line2.push('Renews ' + sub.renews);
                else if (sub.canceled) line2.push('Cancelled ' + sub.canceled);
                if (line2.length) html += '<div style="font-size:11px;color:#888">' + escapeHtml(line2.join('   ·   ')) + '</div>';

                
                
                if (sub.status === 'active' && sub.billable) {
                    html += '<div style="margin-top:8px">';
                    html += '<button type="button" class="impulse-btn-sm impulse-member-suspend" data-customer-id="' + c.id + '" data-confirm="0" style="height:24px;padding:0 10px;font-size:10px">Suspend membership</button>';
                    html += '</div>';
                } else if (sub.status === 'paused') {
                    html += '<div style="margin-top:8px">';
                    if (sub.has_saved_card) {
                        html += '<button type="button" class="impulse-btn-sm impulse-member-reactivate" data-customer-id="' + c.id + '" data-confirm="0" style="height:24px;padding:0 10px;font-size:10px">Reactivate membership</button>';
                    } else {
                        html += '<span style="font-size:10px;color:#888">Suspended. No card on file, so reactivating needs a re-enroll through the site.</span>';
                    }
                    html += '</div>';
                }
                html += '</div>';
            } else {
                
                html += '<div class="impulse-detail-section" style="font-size:11px;color:#888">';
                html += '<span>' + c.order_count + ' ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.order.toLowerCase() : 'order') + (c.order_count !== 1 ? 's' : '') + '</span>';
                if (totalSpent > 0) html += '<span style="margin-left:6px">· ' + currency + totalSpent.toFixed(2) + ' ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.spent.toLowerCase() : 'spent') + '</span>';
                if (c.last_order) html += '<span style="margin-left:6px">· Last ' + escapeHtml(c.last_order) + '</span>';
                html += '</div>';
            }

            if (c.loyalty_points !== null && c.loyalty_points !== undefined) {
                html += '<div class="impulse-detail-section">';
                html += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:4px">';
                html += '<span style="font-size:11px;color:#aaa">Loyalty</span>';
                html += '<button type="button" class="impulse-btn-sm" id="loyalty-adjust-toggle" style="height:22px;padding:0 8px;font-size:10px" data-customer-id="' + c.id + '">Adjust</button>';
                html += '</div>';
                html += '<div style="display:flex;align-items:center;justify-content:space-between">';
                html += '<span style="font-size:12px;font-weight:600;color:#e0e0e0" id="loyalty-points-display">' + c.loyalty_points.toLocaleString() + ' pts</span>';
                html += '<span style="font-size:11px;color:#555;text-transform:capitalize">' + escapeHtml(c.loyalty_tier) + '</span>';
                html += '</div>';
                html += '<div id="loyalty-adjust-form" style="display:none;margin-top:6px">';
                html += '<div style="display:flex;gap:4px;align-items:center">';
                html += '<input type="text" inputmode="numeric" id="loyalty-adjust-delta" placeholder="e.g. -50 or 100" style="flex:1">';
                html += '<button type="button" id="loyalty-adjust-save" class="impulse-btn-sm" data-customer-id="' + c.id + '" style="height:26px">Apply</button>';
                html += '</div>';
                html += '<input type="text" id="loyalty-adjust-reason" placeholder="Reason (optional)" style="width:100%;margin-top:4px">';
                html += '</div></div>';
            }

            if (c.gift_balance) {
                html += '<div class="impulse-detail-section">';
                html += '<div style="display:flex;align-items:center;justify-content:space-between">';
                html += '<span style="font-size:11px;color:#aaa">Gift Card Balance</span>';
                html += '<span style="font-size:12px;font-weight:600;color:#e0e0e0">' + currency + parseFloat(c.gift_balance).toFixed(2) + '</span>';
                html += '</div></div>';
            }

            if (c.orders && c.orders.length) {
                html += '<div class="impulse-detail-section">';
                html += '<div style="font-size:11px;color:#aaa;margin-bottom:6px">' + ((window.Impulse && window.Impulse.storeType === 'memberships') ? 'Payments' : 'Recent Orders') + '</div>';
                var showOrders = c.orders.slice(0, 3);
                showOrders.forEach(function(o) {
                    html += '<div class="impulse-client-order-row" data-order-id="' + o.id + '">';
                    html += '<span class="impulse-status impulse-status-' + escapeHtml(o.status) + '" style="font-size:10px">' + escapeHtml(o.status.charAt(0).toUpperCase() + o.status.slice(1)) + '</span>';
                    html += '<span style="flex:1"></span>';
                    html += '<span style="color:#e0e0e0;font-weight:500;font-size:11px">' + currency + parseFloat(o.total).toFixed(2) + '</span>';
                    html += '</div>';
                });
                if (c.orders.length > 3) {
                    html += '<div style="font-size:10px;color:#555;margin-top:4px">+ ' + (c.orders.length - 3) + ' more</div>';
                }
                html += '</div>';
            }

            if (c.salon) html += renderSalonCRM(c);
            html += '</div>';
            $content.html(html);

            var $noteSection = $('<div style="padding:0 12px 14px">' +
                '<div style="font-size:11px;color:#aaa;margin-bottom:4px">Note</div>' +
                '<textarea id="client-note-textarea" placeholder="Internal note — visible to Instagent and admin only..." rows="3" style="width:100%;min-height:54px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;font-size:11px;font-family:inherit;padding:6px 8px;resize:vertical;box-sizing:border-box;line-height:1.5"></textarea>' +
                '<div style="display:flex;justify-content:space-between;margin-top:4px;align-items:center">' +
                '<button type="button" id="btn-delete-client" class="impulse-btn-sm" data-customer-id="' + c.id + '" style="height:22px;padding:0 8px;font-size:10px">Delete ' + ((window.Impulse && window.Impulse.storeLabels) ? window.Impulse.storeLabels.customer : 'Client') + '</button>' +
                '<button type="button" id="client-note-save" class="impulse-btn-sm" data-customer-id="' + c.id + '" style="height:22px;padding:0 10px;font-size:10px">Save</button>' +
                '</div></div>');
            $content.append($noteSection);

            $.post(window.Impulse.ajaxUrl, {
                action: 'instinctor_get_client_note',
                nonce: window.Impulse.adminNonce,
                customer_id: c.id
            }, function(r) {
                if (r.success && r.data.note) $('#client-note-textarea').val(r.data.note);
            });
        });
    }

    $(document).on('click', '#client-note-save', function() {
        var customerId = $(this).data('customer-id');
        var note = $('#client-note-textarea').val().trim();
        var $btn = $(this).prop('disabled', true).text('…');
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_save_client_note',
            nonce: window.Impulse.adminNonce,
            customer_id: customerId,
            note: note
        }, function(r) {
            $btn.prop('disabled', false).text('Save');
            if (r.success) {
                showImpulseToast(note ? 'Note saved' : 'Note cleared');
            } else {
                showImpulseToast(r.data || 'Failed to save note', 'error');
            }
        }).fail(function() {
            $btn.prop('disabled', false).text('Save');
            showImpulseToast('Network error', 'error');
        });
    });

    $(document).on('click', '#member-edit-toggle', function() {
        $('#member-edit-form').slideDown(120);
        $(this).hide();
        $('#member-edit-first').focus();
    });
    $(document).on('click', '#member-edit-cancel', function() {
        $('#member-edit-form').slideUp(120);
        $('#member-edit-toggle').show();
    });
    $(document).on('click', '#member-edit-save', function() {
        var customerId = $(this).data('customer-id');
        var first  = ($('#member-edit-first').val() || '').trim();
        var last   = ($('#member-edit-last').val() || '').trim();
        var amount = $('#member-edit-amount').length ? ($('#member-edit-amount').val() || '').trim() : '';
        if (amount !== '' && !(parseFloat(amount) > 0)) { showImpulseToast('Enter a valid amount', 'error'); return; }
        var $btn = $(this).prop('disabled', true).text('…');
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_update_member',
            nonce: window.Impulse.adminNonce,
            customer_id: customerId,
            first_name: first,
            last_name: last,
            amount: amount
        }, function(r) {
            $btn.prop('disabled', false).text('Save');
            if (r.success) {
                showImpulseToast(r.data && r.data.warning ? r.data.warning : 'Member updated');
                if (typeof loadClientsCenter === 'function') loadClientsCenter(false); 
                loadCustomerDetail(customerId);          
            } else {
                showImpulseToast((r.data && r.data.message) ? r.data.message : 'Update failed', 'error');
            }
        }).fail(function() {
            $btn.prop('disabled', false).text('Save');
            showImpulseToast('Network error', 'error');
        });
    });

    function memberBillingAction($btn, action, confirmLabel, workingLabel) {
        if ($btn.attr('data-confirm') !== '1') {
            $btn.attr('data-confirm', '1').text(confirmLabel);
            setTimeout(function() { if ($btn.attr('data-confirm') === '1') $btn.attr('data-confirm', '0').text($btn.data('idle-label')); }, 4000);
            return;
        }
        var customerId = $btn.data('customer-id');
        $btn.prop('disabled', true).text(workingLabel);
        $.post(window.Impulse.ajaxUrl, {
            action: action,
            nonce: window.Impulse.adminNonce,
            customer_id: customerId
        }, function(r) {
            if (r.success) {
                showImpulseToast(action === 'instinctor_suspend_member' ? 'Membership suspended, billing stopped' : 'Membership reactivated');
                if (typeof loadClientsCenter === 'function') loadClientsCenter(false);
                loadCustomerDetail(customerId);
            } else {
                $btn.prop('disabled', false).attr('data-confirm', '0').text($btn.data('idle-label'));
                showImpulseToast((r.data && r.data.message) ? r.data.message : 'Action failed', 'error');
            }
        }).fail(function() {
            $btn.prop('disabled', false).attr('data-confirm', '0').text($btn.data('idle-label'));
            showImpulseToast('Network error', 'error');
        });
    }
    $(document).on('click', '.impulse-member-suspend', function() {
        var $b = $(this); $b.data('idle-label', 'Suspend membership');
        memberBillingAction($b, 'instinctor_suspend_member', 'Confirm suspend?', 'Suspending…');
    });
    $(document).on('click', '.impulse-member-reactivate', function() {
        var $b = $(this); $b.data('idle-label', 'Reactivate membership');
        memberBillingAction($b, 'instinctor_reactivate_member', 'Confirm reactivate?', 'Reactivating…');
    });

    $(document).on('click', '#loyalty-adjust-toggle', function() {
        $('#loyalty-adjust-form').toggle();
        if ($('#loyalty-adjust-form').is(':visible')) $('#loyalty-adjust-delta').focus();
    });

    $(document).on('click', '#loyalty-adjust-save', function() {
        var customerId = $(this).data('customer-id');
        var delta  = parseInt($('#loyalty-adjust-delta').val(), 10);
        var reason = $('#loyalty-adjust-reason').val().trim() || 'Manual adjustment';
        if (!delta) { showImpulseToast('Enter a non-zero amount', 'error'); return; }
        var $btn = $(this).prop('disabled', true).text('…');
        $.post(window.Impulse.ajaxUrl, {
            action: 'instinctor_adjust_loyalty_points',
            nonce: window.Impulse.adminNonce,
            customer_id: customerId,
            delta: delta,
            reason: reason
        }, function(res) {
            $btn.prop('disabled', false).text('Apply');
            if (res.success) {
                $('#loyalty-points-display').text(res.data.points.toLocaleString() + ' pts');
                $('#loyalty-adjust-form').hide();
                $('#loyalty-adjust-delta').val('');
                $('#loyalty-adjust-reason').val('');
                showImpulseToast('Points adjusted');
            } else {
                showImpulseToast('Failed to adjust points', 'error');
            }
        });
    });

    $(document).on('click', '.impulse-client-order-row', function() {
        var orderId = $(this).data('order-id');
        switchStoreSection('orders');
        setOrdersTabMode('orders');
        setTimeout(function() {
            var $item = $('#dashboard-orders-list .impulse-list-item[data-order-id="' + orderId + '"]');
            if ($item.length) selectItem('order', orderId, $item);
            loadOrderDetail(orderId);
        }, 50);
    });

    $(document).on('click', '.impulse-order-client-link', function() {
        var customerId = $(this).data('customer-id');
        setOrdersTabMode('clients');
        if (!clientsState.initialized) initClientsWorkspace();
        loadCustomerDetail(customerId);
    });

    

    function couponNonce() { return window.Impulse.marketingNonce; }
    
    function openCouponForm(coupon, targetId) { showCouponForm(coupon, targetId); }

    function loadCouponList() {
        $.post(ajaxurl, { action: 'instinctor_get_all_coupons', _wpnonce: couponNonce() }, function(res) {
            if (!res.success) return;
            var coupons = res.data.coupons;
            var currency = (window.Impulse.products && window.Impulse.products.currency) || '$';
            var $list = $('#dashboard-coupons-list');
            if (!coupons || !coupons.length) {
                $list.html('<li class="impulse-empty"><div class="impulse-empty-title">No coupons yet</div><div class="impulse-empty-desc">Create discount codes to boost sales.</div></li>');
                return;
            }
            var html = '';
            $.each(coupons, function(_, c) {
                var discount = c.discount_type === 'percent' ? c.amount + '%' : currency + parseFloat(c.amount).toFixed(2);
                var usedTxt = c.usage_count ? '<span style="margin-left:8px;color:#888">Used ' + c.usage_count + '×</span>' : '';
                var statusColor = c.status === 'active' ? '#e0e0e0' : '#555';
                html += '<li class="impulse-list-item" data-coupon-id="' + c.id + '" data-status="' + escapeHtml(c.status) + '">';
                html += '<div class="impulse-list-item-content">';
                html += '<div class="impulse-list-item-title" style="font-family:monospace">' + escapeHtml(c.code) + '</div>';
                html += '<div class="impulse-list-item-subtitle"><span style="color:#999">' + escapeHtml(discount) + ' off</span>' + usedTxt + '</div>';
                html += '</div>';
                html += '<span class="impulse-list-item-meta" style="color:' + statusColor + '">' + escapeHtml(c.status.charAt(0).toUpperCase() + c.status.slice(1)) + '</span>';
                html += '</li>';
            });
            $list.html(html);
        });
    }

    
    var _formCalOpen = {};  
    var _formCalDate = {};

    function formDateBtn(id, val, placeholder) {
        var disp = '';
        if (val) {
            var parts = val.split('-');
            if (parts.length === 3) disp = parseInt(parts[1]) + '/' + parseInt(parts[2]) + '/' + parts[0];
        }
        var btnStyle = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:' + (disp ? '#e0e0e0' : '#555') + ';font-size:11px;padding:0 8px;text-align:left;cursor:pointer;box-sizing:border-box;display:flex;align-items:center;user-select:none';
        return '<div style="position:relative" id="fdp-wrap-' + id + '">'
            + '<button type="button" id="fdp-btn-' + id + '" style="' + btnStyle + '">' + (disp || placeholder) + '</button>'
            + '<input type="hidden" id="' + id + '" value="' + (val || '') + '">'
            + '</div>';
    }

    function openFormDatePicker(hiddenId) {
        
        Object.keys(_formCalOpen).forEach(function(k) {
            if (_formCalOpen[k]) closeFormDatePicker(k);
        });
        _formCalOpen[hiddenId] = true;
        if (!_formCalDate[hiddenId]) _formCalDate[hiddenId] = new Date();

        var popup = buildFormCalPopup(hiddenId, _formCalDate[hiddenId].getFullYear(), _formCalDate[hiddenId].getMonth());
        var rect = document.getElementById('fdp-btn-' + hiddenId).getBoundingClientRect();
        popup.css({ position: 'fixed', top: rect.bottom + 4, left: rect.left, width: Math.max(rect.width, 200), zIndex: 1000030 });
        $('body').append(popup);
        if (rect.bottom + popup.outerHeight() + 4 > window.innerHeight - 8) {
            popup.css('top', rect.top - popup.outerHeight() - 4);
        }
    }

    function closeFormDatePicker(hiddenId) {
        $('#fdp-popup-' + hiddenId).remove();
        _formCalOpen[hiddenId] = false;
    }

    function buildFormCalPopup(hiddenId, year, month) {
        var DAYS = ['S','M','T','W','T','F','S'];
        var MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        var selected = $('#' + hiddenId).val();
        _formCalDate[hiddenId] = new Date(year, month, 1);

        var $pop = $('<div id="fdp-popup-' + hiddenId + '" style="background:#1a1d21;border:1px solid #3a3f44;border-radius:4px;box-shadow:0 4px 16px rgba(0,0,0,0.5);padding:10px;box-sizing:border-box"></div>');
        $pop.on('click', function(e) { e.stopPropagation(); });

        var $hdr = $('<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px"></div>');
        var $prev = $('<button type="button" style="background:none;border:none;color:#888;cursor:pointer;padding:2px 6px;font-size:13px">&#8249;</button>');
        var $next = $('<button type="button" style="background:none;border:none;color:#888;cursor:pointer;padding:2px 6px;font-size:13px">&#8250;</button>');
        var $mo   = $('<span style="font-size:11px;font-weight:600;color:#e0e0e0">' + MONTHS[month] + ' ' + year + '</span>');
        $hdr.append($prev).append($mo).append($next);
        $pop.append($hdr);

        $prev.on('click', function(e) {
            e.stopPropagation();
            month--; if (month < 0) { month = 11; year--; }
            $('#fdp-popup-' + hiddenId).replaceWith(buildFormCalPopup(hiddenId, year, month));
        });
        $next.on('click', function(e) {
            e.stopPropagation();
            month++; if (month > 11) { month = 0; year++; }
            $('#fdp-popup-' + hiddenId).replaceWith(buildFormCalPopup(hiddenId, year, month));
        });

        var $grid = $('<div style="display:grid;grid-template-columns:repeat(7,1fr);gap:2px;text-align:center"></div>');
        DAYS.forEach(function(d) { $grid.append('<div style="font-size:9px;color:#555;padding:2px 0">' + d + '</div>'); });

        var firstDay = new Date(year, month, 1).getDay();
        for (var i = 0; i < firstDay; i++) $grid.append('<div></div>');

        var daysInMonth = new Date(year, month + 1, 0).getDate();
        for (var d = 1; d <= daysInMonth; d++) {
            var mm = ('0' + (month + 1)).slice(-2);
            var dd = ('0' + d).slice(-2);
            var val = year + '-' + mm + '-' + dd;
            var isSel = (val === selected);
            var $day = $('<div data-val="' + val + '" style="font-size:10px;padding:3px 2px;border-radius:3px;cursor:pointer;text-align:center;' + (isSel ? 'background:#3a3f44;color:#fff' : 'color:#999') + '">' + d + '</div>');
            $day.on('mouseenter', function() { $(this).css({ background: '#2a2e33', color: '#e0e0e0' }); });
            $day.on('mouseleave', function() { if ($(this).data('val') !== selected) $(this).css({ background: '', color: '#999' }); });
            $day.on('click', function(e) {
                e.stopPropagation();
                var v = $(this).data('val');
                var parts = v.split('-');
                var disp = parseInt(parts[1]) + '/' + parseInt(parts[2]) + '/' + parts[0];
                selected = v;
                $('#' + hiddenId).val(v).trigger('change');
                $('#fdp-btn-' + hiddenId).text(disp).css('color', '#e0e0e0');
                closeFormDatePicker(hiddenId);
            });
            $grid.append($day);
        }
        $pop.append($grid);
        return $pop;
    }

    $(document).on('click', '[id^="fdp-btn-"]', function(e) {
        e.stopPropagation();
        var hiddenId = this.id.replace('fdp-btn-', '');
        if (_formCalOpen[hiddenId]) { closeFormDatePicker(hiddenId); } else { openFormDatePicker(hiddenId); }
    });
    $(document).on('click.fdpcal', function(e) {
        if (!$(e.target).closest('[id^="fdp-popup-"], [id^="fdp-btn-"]').length) {
            Object.keys(_formCalOpen).forEach(function(k) {
                if (_formCalOpen[k]) closeFormDatePicker(k);
            });
        }
    });

    function showCouponForm(coupon, targetId) {
        var c = coupon || {};
        var isNew = !c.id;
        var currency = (window.Impulse.products && window.Impulse.products.currency) || '$';
        var IS = 'width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:0 8px;font-size:11px;box-sizing:border-box';

        function num(id, val, placeholder) {
            return '<input id="' + id + '" type="text" inputmode="numeric" value="' + escapeHtml(String(val !== undefined && val !== null ? val : '')) + '"'
                + ' placeholder="' + escapeHtml(placeholder || '') + '" style="' + IS + '">';
        }
        function cell(label, content) {
            return '<div><div style="font-size:11px;color:#888;margin-bottom:3px">' + label + '</div>' + content + '</div>';
        }

        var isActive = c.status !== 'inactive';
        var html = '<div style="margin-bottom:10px;display:flex">';
        html += '<button type="button" class="impulse-btn-sm coupon-status-btn' + (isActive ? ' active' : '') + '" data-status="active" style="border-radius:3px 0 0 3px;flex:1">Active</button>';
        html += '<button type="button" class="impulse-btn-sm coupon-status-btn' + (!isActive ? ' active' : '') + '" data-status="inactive" style="border-radius:0 3px 3px 0;flex:1">Inactive</button>';
        html += '</div>';

        html += '<div class="impulse-section-divider" style="margin-top:0">' + (isNew ? 'New Coupon' : 'Edit Coupon') + '</div>';
        html += '<input type="hidden" id="coupon-id" value="' + (c.id || '') + '">';

        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Code</div>';
        html += '<div style="display:flex;gap:6px">';
        html += '<input id="coupon-code" type="text" value="' + escapeHtml(c.code || '') + '" placeholder="SUMMER20"'
            + ' style="flex:1;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:0 8px;font-size:11px;font-family:monospace;box-sizing:border-box;text-transform:uppercase">';
        html += '<button type="button" id="coupon-gen-inline" class="impulse-btn-sm">Generate</button>';
        html += '</div></div>';

        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Type</div><div style="display:flex">';
        html += '<button type="button" class="impulse-btn-sm coupon-type-btn' + (c.discount_type !== 'fixed' ? ' active' : '') + '" data-type="percent" style="border-radius:3px 0 0 3px;flex:1">Percent %</button>';
        html += '<button type="button" class="impulse-btn-sm coupon-type-btn' + (c.discount_type === 'fixed' ? ' active' : '') + '" data-type="fixed" style="border-radius:0 3px 3px 0;flex:1">Fixed ' + escapeHtml(currency) + '</button>';
        html += '</div></div>';

        html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 10px;margin-bottom:8px">';
        html += cell('Amount',         num('coupon-amount',     c.amount || '',               '0'));
        html += cell('Min Order',      num('coupon-min',        c.minimum_amount || '',       'No min'));
        html += cell('Max Discount',   num('coupon-max',        c.maximum_amount || '',       'No limit'));
        html += cell('Per User Limit', num('coupon-limit-user', c.usage_limit_per_user || '', 'Unlimited'));
        html += cell('Usage Limit',    num('coupon-limit',      c.usage_limit || '',          'Unlimited'));
        html += '<div></div>';
        
        html += cell('Start Date',  formDateBtn('coupon-start', c.start_date || '', 'No start'));
        html += cell('Expiry Date', formDateBtn('coupon-end',   c.end_date   || '', 'Never'));
        html += '</div>';

        html += '<div style="margin-bottom:8px"><div style="font-size:11px;color:#888;margin-bottom:3px">Description <span style="color:#555">(internal)</span></div>';
        html += '<input id="coupon-desc" type="text" value="' + escapeHtml(c.description || '') + '" placeholder="Optional note…" style="' + IS + '">';
        html += '</div>';

        html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#e0e0e0;cursor:pointer;margin-bottom:8px">'
            + '<input type="checkbox" id="coupon-free-shipping"' + (c.shipping ? ' checked' : '') + '> Free shipping</label>';

        if (!isNew && c.usage_count) {
            html += '<div style="font-size:11px;color:#555;margin-bottom:8px">Used ' + c.usage_count + ' time' + (c.usage_count !== 1 ? 's' : '') + '</div>';
        }
        if (!isNew) {
            html += '<button type="button" class="impulse-btn-sm" id="coupon-delete-btn" style="color:#555">Delete Coupon</button>';
        }

        var _couponTarget = '#' + (targetId || (ordersTabMode === 'clients' ? 'clients-right-body' : 'settings-detail-content'));        $(_couponTarget).html(html);

        var _couponTimer = null;
        function scheduleSave() { clearTimeout(_couponTimer); _couponTimer = setTimeout(saveCoupon, 800); }
        $(_couponTarget).on('input change', 'input', scheduleSave);
        $(_couponTarget).on('click', '.coupon-type-btn, .coupon-status-btn', function() { setTimeout(scheduleSave, 50); });
    }

    function saveCoupon() {
        var code = $('#coupon-code').val().trim();
        if (!code) return;
        
        var $formContainer = $('#clients-right-body').length ? $('#clients-right-body') : $('#settings-detail-content');
        $.post(ajaxurl, {
            action:               'instinctor_save_coupon',
            _wpnonce:             couponNonce(),
            coupon_id:            $('#coupon-id').val(),
            code:                 code,
            discount_type:        $('.coupon-type-btn.active').data('type') || 'percent',
            amount:               $('#coupon-amount').val(),
            description:          $('#coupon-desc').val(),
            minimum_amount:       $('#coupon-min').val(),
            maximum_amount:       $('#coupon-max').val(),
            usage_limit:          $('#coupon-limit').val(),
            usage_limit_per_user: $('#coupon-limit-user').val(),
            start_date:           $('#coupon-start').val(),
            end_date:             $('#coupon-end').val(),
            shipping:        $('#coupon-free-shipping').is(':checked') ? 1 : 0,
            status:               $('.coupon-status-btn.active').data('status') || 'active'}, function(res) {
            if (res.success) {
                if (!$('#coupon-id').val() && res.data && res.data.id) {
                    $('#coupon-id').val(res.data.id);
                    if (!$('#coupon-delete-btn').length) {
                        $formContainer.append('<button type="button" class="impulse-btn-sm" id="coupon-delete-btn" style="color:#555;margin-top:8px;display:block">Delete Coupon</button>');
                    }
                }
                showImpulseToast('Coupon saved');
                if (ordersTabMode === 'clients') loadClientsCenter();
                else loadCouponList();
            } else {
                showImpulseToast((res.data && res.data.message) || 'Error saving coupon', 'error');
            }
        });
    }

    function showCouponDetail($el) {
        var id = $el.data('coupon-id');
        $.post(ajaxurl, { action: 'instinctor_get_coupon_detail', _wpnonce: couponNonce(), coupon_id: id }, function(res) {
            if (res.success) showCouponForm(res.data);
            else showImpulseToast('Failed to load coupon', 'error');
        });
    }

    $(document).on('click', '#impulse-add-coupon', function() {
        $('.impulse-list-item').removeClass('active');
        showCouponForm(null);
    });

    $(document).on('click', '#coupon-gen-inline', function() {
        var code = Math.random().toString(36).substring(2,6).toUpperCase() + Math.random().toString(36).substring(2,6).toUpperCase();
        $('#coupon-code').val(code).trigger('input'); 
    });

    $(document).on('input', '#coupon-code', function() {
        var pos = this.selectionStart;
        this.value = this.value.toUpperCase();
        this.setSelectionRange(pos, pos);
    });

    $(document).on('click', '.coupon-type-btn', function() { $('.coupon-type-btn').removeClass('active'); $(this).addClass('active'); });
    $(document).on('click', '.coupon-status-btn', function() { $('.coupon-status-btn').removeClass('active'); $(this).addClass('active'); });

    $(document).on('click', '#coupon-delete-btn', function() {
        if (!window.impulseConfirm('Delete this coupon?')) return;
        var id = $('#coupon-id').val();
        var $formContainer = $('#clients-right-body').length ? $('#clients-right-body') : $('#settings-detail-content');
        $.post(ajaxurl, { action: 'instinctor_delete_coupon', _wpnonce: couponNonce(), coupon_id: id }, function(res) {
            if (res.success) {
                showImpulseToast('Coupon deleted');
                $formContainer.html('');
                if (ordersTabMode === 'clients') loadClientsCenter();
                else loadCouponList();
            } else showImpulseToast('Error deleting coupon', 'error');
        });
    });

    function showRMADetail($el) {
        var rmaNumber = $el.find('.impulse-list-item-title').text().split('·')[0].trim();
        var order = $el.find('.impulse-list-item-subtitle span').first().text();
        var product = $el.data('product') || 'Product';
        var reason = $el.data('reason') || 'Defective item';
        var customer = $el.data('customer') || 'Customer';

        
        var html = '<div style="padding:16px">';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Order</label><div style="color:#e0e0e0">' + order + '</div></div>';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Product</label><div style="color:#ccc;font-size:11px">' + product + '</div></div>';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Reason</label><div style="color:#ccc;font-size:11px">' + reason + '</div></div>';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Customer</label><div style="color:#aaa;font-size:11px">' + customer + '</div></div>';
        html += '<div style="display:flex;gap:8px;margin-top:16px">';
        html += '<button class="impulse-btn impulse-btn-sm btn-approve-rma" style="background:#2a2e33;border-color:#e0e0e0;color:#fff;flex:1">Approve Return</button>';
        html += '<button class="impulse-btn impulse-btn-sm btn-reject-rma" style="flex:1">Reject</button>';
        html += '</div></div>';
        
        $('#settings-detail-content').html(html);
    }

    function showBookingDetail($el) {
        var service = $el.find('.impulse-list-item-title').text();
        var datetime = $el.find('.impulse-list-item-subtitle span').first().text();
        var customer = $el.data('customer') || 'Customer';
        var status = $el.data('status') || 'pending';

        
        var html = '<div style="padding:16px">';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Service</label><div style="color:#e0e0e0">' + service + '</div></div>';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Date & Time</label><div style="color:#ccc;font-size:11px">' + datetime + '</div></div>';
        html += '<div class="impulse-detail-section"><label style="font-size:11px;color:#aaa;display:block;margin-bottom:4px">Customer</label><div style="color:#aaa;font-size:11px">' + customer + '</div></div>';
        
        if (status === 'pending') {
            html += '<div style="display:flex;gap:8px;margin-top:16px">';
            html += '<button class="impulse-btn impulse-btn-sm btn-confirm-booking" style="background:#2a2e33;border-color:#e0e0e0;color:#fff;flex:1">Confirm</button>';
            html += '<button class="impulse-btn impulse-btn-sm btn-cancel-booking" style="flex:1">Cancel</button>';
            html += '</div>';
        } else {
            html += '<button class="impulse-btn impulse-btn-sm btn-cancel-booking" style="width:100%;margin-top:16px">Cancel Booking</button>';
        }
        html += '</div>';
        
        $('#settings-detail-content').html(html);
    }

    

    
    function resetDetailPanel() {
        selectedItemId = null;
        selectedItemType = null;
        $('#settings-detail-content').empty();
    }

    

    

    
    $(document).on('click', '#settings-email-toggle', function() {
        var $emails = $('#email-list-wrap');
        $emails.toggle();
        if ($emails.is(':visible')) {
            $('#settings-chat-body').slideUp(150);
        }
    });

    $(document).on('click', '#settings-chat-toggle', function() {
        var $chat = $('#settings-chat-body');
        var isOpening = $chat.is(':hidden');
        $chat.slideToggle(150);
        if (isOpening) {
            $('#email-list-wrap').hide();
        }
    });

    function renderEmailsRightPanel() {
        var states = window._emailTemplateStates || {};
        var html = '';

        $.each(states, function(key, t) {
            var isOn = t.enabled;
            html += '<div class="impulse-email-row" data-email-key="' + key + '" style="display:flex;align-items:center;justify-content:space-between;padding:5px 12px;border-bottom:1px solid #2a2e33;cursor:pointer">';
            html += '<span class="email-row-label" style="font-size:11px;color:#e0e0e0;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-right:8px">' + escapeHtml(t.label) + '</span>';
            html += '<input type="checkbox" class="email-enabled-cb" data-key="' + key + '"' + (isOn ? ' checked' : '') + ' style="flex-shrink:0">';
            html += '</div>';
        });

        html += '<div class="impulse-email-row" id="email-footer-row" style="display:flex;align-items:center;padding:7px 12px;cursor:pointer;margin-top:4px">';
        html += '<span style="font-size:11px;color:#888">Footer Settings</span>';
        html += '</div>';

        $('#email-list-wrap').html(html);
        if (typeof window.upgradeCheckboxes === 'function') window.upgradeCheckboxes(document.getElementById('email-list-wrap'));
    }

    $(document).on('change', '.email-enabled-cb', function(e) {
        e.stopPropagation();
        var key = $(this).data('key');
        var enabled = $(this).is(':checked') ? 1 : 0;
        if (window._emailTemplateStates && window._emailTemplateStates[key]) {
            window._emailTemplateStates[key].enabled = !!enabled;
        }
        $.post(ajaxurl, {
            action: 'instinctor_toggle_email_template',
            nonce: window.Impulse.adminNonce,
            key: key,
            enabled: enabled
        }, function(res) {
            if (!res.success && typeof showImpulseToast === 'function') showImpulseToast('Failed to update', 'error');
        });
    });

    $(document).on('click', '.impulse-email-row[data-email-key]', function(e) {
        if ($(e.target).closest('.impulse-cb,.email-enabled-cb').length) return;
        var key = $(this).data('email-key');
        $('.impulse-email-row').css('background', '');
        $(this).css('background', '#2a2e33');
        $.post(ajaxurl, {
            action: 'instinctor_get_email_template',
            nonce: window.Impulse.adminNonce,
            key: key
        }, function(res) {
            if (res.success) showEmailEditor(key, res.data);
        });
    });

    $(document).on('click', '#email-footer-row', function() {
        $('.impulse-email-row').css('background', '');
        $(this).css('background', '#2a2e33');
        showEmailFooterEditor();
    });

    function showEmailEditor(key, data) {
        var states = window._emailTemplateStates || {};
        var label = (states[key] && states[key].label) ? states[key].label : key;

        var html = '';
        html += '<div style="margin-bottom:10px">';
        html += '<div style="font-size:11px;color:#888;margin-bottom:4px">Subject</div>';
        html += '<input type="text" class="email-detail-subject email-autosave" data-key="' + key + '" value="' + escapeHtml(data.subject || '') + '" placeholder="Email subject…" style="width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:0 8px;font-size:11px;box-sizing:border-box">';
        html += '</div>';
        html += '<div style="margin-bottom:10px">';
        html += '<div style="font-size:11px;color:#888;margin-bottom:4px">Heading</div>';
        html += '<input type="text" class="email-detail-heading email-autosave" data-key="' + key + '" value="' + escapeHtml(data.heading || '') + '" placeholder="Email heading…" style="width:100%;height:26px;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:0 8px;font-size:11px;box-sizing:border-box">';
        html += '</div>';
        html += '<div style="margin-bottom:10px">';
        html += '<div style="font-size:11px;color:#888;margin-bottom:4px">Body</div>';
        html += '<textarea class="email-detail-body email-autosave" data-key="' + key + '" placeholder="Email content…" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:6px 8px;font-size:11px;box-sizing:border-box;resize:none;display:block;overflow:hidden;min-height:80px">' + escapeHtml(data.body || '') + '</textarea>';
        html += '</div>';
        html += '<div style="background:#1a1d21;border-radius:3px;padding:8px 10px;margin-bottom:10px">';
        html += '<div style="font-size:10px;color:#555;margin-bottom:4px;text-transform:uppercase;letter-spacing:0.4px">Variables</div>';
        html += '<div style="display:flex;flex-wrap:wrap;gap:4px">';
        var vars = ['{customer_name}','{order_number}','{order_total}','{store_name}','{tracking_number}','{reset_link}','{order_details}'];
        vars.forEach(function(v) {
            html += '<code style="font-size:11px;background:#2a2e33;color:#aaa;padding:2px 5px;border-radius:2px">' + v + '</code>';
        });
        html += '</div></div>';
        html += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#ccc;cursor:pointer">';
        html += '<input type="checkbox" class="email-detail-footer email-autosave" data-key="' + key + '"' + (data.include_footer !== false ? ' checked' : '') + '> Include footer';
        html += '</label>';

        $('#email-modal-title').text(label);
        $('#email-modal-body').html(html);
        $('#email-modal-body').data('mode', 'email').data('key', key);
        $('#email-modal-saved').css('opacity', 0);
        $('#email-modal-test').show();
        $('#email-editor-modal').css('display', 'flex');

        var $ta = $('#email-modal-body .email-detail-body');
        function expandTa(el) { el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; }
        expandTa($ta[0]);
        $ta.on('input', function() { expandTa(this); });
    }

    $(document).on('click', '#email-modal-close', function() {
        $('#email-editor-modal').hide();
    });
    
    $(document).on('click', '#email-editor-modal', function(e) {
        if (e.target === this) $('#email-editor-modal').hide();
    });

    $(document).on('click', '#email-modal-save', function() {
        var mode = $('#email-modal-body').data('mode');
        if (mode === 'footer') {
            saveFooterSettings();
        } else {
            var key = $('#email-modal-body').data('key');
            if (!key) return;
            $.post(ajaxurl, {
                action: 'instinctor_save_email_template',
                nonce: window.Impulse.adminNonce,
                key: key,
                subject: $('#email-modal-body .email-detail-subject').val(),
                heading: $('#email-modal-body .email-detail-heading').val(),
                body: $('#email-modal-body .email-detail-body').val(),
                include_footer: $('#email-modal-body .email-detail-footer').is(':checked') ? 1 : 0
            }, function(res) {
                if (res.success) {
                    var $ind = $('#email-modal-saved');
                    $ind.css('opacity', 1);
                    setTimeout(function() { $ind.css('opacity', 0); }, 2000);
                } else {
                    if (typeof showImpulseToast === 'function') showImpulseToast('Error saving', 'error');
                }
            });
        }
    });

    $(document).on('click', '#email-modal-test', function() {
        var key = $('#email-modal-body').data('key');
        if (!key) return;
        $(this).text('Sending…').prop('disabled', true);
        var self = this;
        $.post(ajaxurl, {
            action: 'instinctor_send_test_email',
            nonce: window.Impulse.adminNonce,
            key: key
        }, function(res) {
            $(self).text('Send Test').prop('disabled', false);
            showImpulseToast(res.success ? 'Test email sent' : 'Failed to send', res.success ? 'success' : 'error');
        });
    });

    var _emailSaveTimer = null;

    
    function showEmailFooterEditor() {
        $.post(ajaxurl, {
            action: 'instinctor_get_email_footer_settings',
            nonce: window.Impulse.adminNonce
        }, function(res) {
            if (res.success) renderFooterEditor(res.data);
        });
    }

    function renderFooterEditor(settings) {
        var html = '';
        
        html += '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;margin-bottom:12px">';

        html += '<div>';
        html += '<div style="font-size:11px;color:#ccc;margin-bottom:5px">Store Name</div>';
        html += '<input type="checkbox" id="footer-show-store-name"' + (settings.show_store_name !== false ? ' checked' : '') + '>';
        html += '<div style="font-size:11px;color:#ccc;margin-top:10px;margin-bottom:5px">Address</div>';
        html += '<input type="checkbox" id="footer-show-address"' + (settings.show_address !== false ? ' checked' : '') + '>';
        html += '</div>';

        html += '<div style="text-align:center">';
        html += '<div style="font-size:11px;color:#ccc;margin-bottom:5px">Logo</div>';
        html += '<input type="checkbox" id="footer-show-logo"' + (settings.show_logo ? ' checked' : '') + '>';
        html += '</div>';

        html += '<div style="text-align:right">';
        html += '<div style="font-size:11px;color:#ccc;margin-bottom:5px">Email</div>';
        html += '<input type="checkbox" id="footer-show-email"' + (settings.show_email !== false ? ' checked' : '') + '>';
        html += '<div style="font-size:11px;color:#ccc;margin-top:10px;margin-bottom:5px">Phone</div>';
        html += '<input type="checkbox" id="footer-show-phone"' + (settings.show_phone !== false ? ' checked' : '') + '>';
        html += '</div>';

        html += '</div>'; 

        html += '<div style="font-size:11px;color:#888;margin-bottom:6px">Text Alignment</div>';
        html += '<div style="display:flex;gap:0;margin-bottom:12px">';
        ['left','center','right'].forEach(function(align) {
            var active = (settings.text_align === align) || (!settings.text_align && align === 'center');
            html += '<button type="button" class="impulse-btn-sm footer-align' + (active ? ' active' : '') + '" data-align="' + align + '" style="border-radius:0;flex:1;text-transform:capitalize">' + align.charAt(0).toUpperCase() + align.slice(1) + '</button>';
        });
        html += '</div>';
        html += '<div style="margin-bottom:4px">';
        html += '<div style="font-size:11px;color:#888;margin-bottom:4px">Custom Footer Text</div>';
        html += '<textarea id="footer-custom-text" rows="3" style="width:100%;background:#2a2e33;border:1px solid #3a3f44;border-radius:3px;color:#e0e0e0;padding:6px 8px;font-size:11px;box-sizing:border-box;resize:vertical;display:block" placeholder="Additional text…">' + escapeHtml(settings.custom_text || '') + '</textarea>';
        html += '</div>';

        $('#email-modal-title').text('Footer Settings');
        $('#email-modal-body').html(html).data('mode', 'footer').data('key', '');
        $('#email-modal-saved').css('opacity', 0);
        $('#email-modal-test').hide();
        $('#email-editor-modal').css('display', 'flex');
    }

    function saveFooterSettings() {
        $.post(ajaxurl, {
            action: 'instinctor_save_email_footer_settings',
            nonce: window.Impulse.adminNonce,
            show_logo:       $('#footer-show-logo').is(':checked') ? 1 : 0,
            show_store_name: $('#footer-show-store-name').is(':checked') ? 1 : 0,
            show_address:    $('#footer-show-address').is(':checked') ? 1 : 0,
            show_email:      $('#footer-show-email').is(':checked') ? 1 : 0,
            show_phone:      $('#footer-show-phone').is(':checked') ? 1 : 0,
            text_align:      $('.footer-align.active').data('align') || 'center',
            custom_text:     $('#footer-custom-text').val()
        }, function(res) {
            if (res.success) {
                var $ind = $('#email-modal-saved');
                $ind.css('opacity', 1);
                setTimeout(function() { $ind.css('opacity', 0); }, 2000);
                if (typeof showImpulseToast === 'function') showImpulseToast('Footer saved');
            } else {
                if (typeof showImpulseToast === 'function') showImpulseToast('Error saving footer', 'error');
            }
        });
    }

    var _footerSaveTimer = null;
    $(document).on('click', '.footer-align', function() {
        if ($('#email-modal-body').data('mode') !== 'footer') return;
        $('.footer-align').removeClass('active');
        $(this).addClass('active');
        clearTimeout(_footerSaveTimer);
        _footerSaveTimer = setTimeout(saveFooterSettings, 800);
    });
    $(document).on('change input', '#footer-show-logo, #footer-show-store-name, #footer-show-address, #footer-show-email, #footer-show-phone, #footer-custom-text', function() {
        if ($('#email-modal-body').data('mode') !== 'footer') return;
        clearTimeout(_footerSaveTimer);
        _footerSaveTimer = setTimeout(saveFooterSettings, 800);
    });

    window.showImpulseToast = showToast;

    
    $(function() {
        var _storeGrid = document.querySelector('.impulse-store-grid');
        if (_storeGrid && typeof window.upgradeCheckboxes === 'function') {
            var _storeObserver = new MutationObserver(function(mutations) {
                mutations.forEach(function(m) {
                    if (m.addedNodes.length) window.upgradeCheckboxes(m.target);
                });
            });
            _storeObserver.observe(_storeGrid, { childList: true, subtree: true });
        }
    });

})(jQuery);
