(function($) {
    'use strict';
    
    function formatBytes(bytes) {
        if (bytes === 0) return '0 B';
        var k = 1024, sizes = ['B', 'KB', 'MB', 'GB'];
        var i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }
    window.impulseFormatBytes = formatBytes; 
    
    var imgoptStats = { optimized: 0, saved: 0, remaining: 0 };
    
    function loadImgOptStats() {
        $.post(ajaxurl, { action: 'instinctor_imgopt_stats', nonce: window.Impulse.adminNonce }, function(r) {
            if (!r.success) return;
            var d = r.data;
            imgoptStats.optimized = d.optimized_count;
            imgoptStats.saved = d.total_saved;
            imgoptStats.remaining = d.unoptimized;
        });
    }
    
    
    $(document).on('click', '[data-settings-tab="images"]', function() {
        loadImgOptStats();
    });
    
    
    $(document).on('change', '#imgopt-webp', function() {
        $('#imgopt-webp-settings').toggle(this.checked);
    });

    
    $(document).on('click', '#imgopt-advanced-toggle', function() {
        var $panel = $('#imgopt-advanced-panel');
        var $icon  = $('#imgopt-advanced-icon');
        var open   = $panel.is(':visible');
        $panel.slideToggle(150);
        $icon.attr('points', open ? '6 9 12 15 18 9' : '18 15 12 9 6 15');
    });

    
    function saveImgoptSettings() {
        $.post(ajaxurl, {
            action: 'instinctor_imgopt_save',
            nonce: window.Impulse.adminNonce,
            enabled:     $('#imgopt-enabled').is(':checked') ? 1 : 0,
            max_width:   $('#imgopt-max-width').val(),
            max_height:  $('#imgopt-max-height').val(),
            quality:     $('#imgopt-quality').val(),
            webp:        $('#imgopt-webp').is(':checked') ? 1 : 0,
            webp_quality: $('#imgopt-webp-quality').val()
        });
    }
    var _imgoptSaveTimer = null;
    $(document).on('change input', '#imgopt-enabled, #imgopt-webp, #imgopt-max-width, #imgopt-max-height', function() {
        clearTimeout(_imgoptSaveTimer);
        _imgoptSaveTimer = setTimeout(saveImgoptSettings, 600);
    });
    $(document).on('change', '#imgopt-quality, #imgopt-webp-quality', function() {
        clearTimeout(_imgoptSaveTimer);
        _imgoptSaveTimer = setTimeout(saveImgoptSettings, 600);
    });
    
    
    $(document).on('click', '#imgopt-bulk-start', function() {
        var btn = $(this);
        btn.prop('disabled', true).text('Processing...');
        $('#imgopt-bulk-progress').show();
        var totalProcessed = 0, totalToProcess = imgoptStats.remaining || 0;
        if (totalToProcess === 0) totalToProcess = 1;
        
        function runBatch() {
            $.post(ajaxurl, {
                action: 'instinctor_imgopt_bulk',
                nonce: window.Impulse.adminNonce,
                batch_size: 5
            }, function(r) {
                if (!r.success) {
                    btn.prop('disabled', false).text('Optimize All');
                    return;
                }
                var d = r.data;
                totalProcessed += d.results.length;
                var pct = Math.min(100, Math.round((totalProcessed / totalToProcess) * 100));
                $('#imgopt-bulk-bar').css('width', pct + '%');
                $('#imgopt-bulk-status').text(totalProcessed + ' of ' + totalToProcess + ' processed (' + formatBytes(d.batch_saved) + ' saved this batch)');
                
                if (d.remaining > 0) {
                    runBatch();
                } else {
                    btn.prop('disabled', false).text('Optimize All');
                    loadImgOptStats();
                    if (typeof showToast === 'function') window.showToast('Bulk optimization complete');
                }
            }).fail(function() {
                btn.prop('disabled', false).text('Optimize All');
            });
        }
        runBatch();
    });
    

    


    var _storeTypeMap = {
        physical_goods: { downloads: false, returns: true,  cart: true,  address: true  },
        digital_goods:  { downloads: true,  returns: false, cart: true,  address: false },
        services:       { downloads: false, returns: false, cart: false, address: true  },
        salon:          { downloads: false, returns: false, cart: false, address: true  },
        home_services:  { downloads: false, returns: false, cart: false, address: true  },
        subscriptions:  { downloads: false, returns: false, cart: true,  address: false },
        memberships:    { downloads: false, returns: false, cart: false, address: false },
        mixed:          { downloads: true,  returns: true,  cart: true,  address: true  }
    };

    function applyStoreTypeVisibility(type) {
        var cfg = _storeTypeMap[type] || _storeTypeMap['mixed'];
        $('#settings-section-downloads').toggle(cfg.downloads);
        $('#settings-section-returns').toggle(cfg.returns);
        $('#settings-storeinfo-address').toggle(cfg.address);
    }

    
    applyStoreTypeVisibility($('#settings-store-type').val() || window.Impulse.storeType);

    
    $(document).on('change', '#settings-store-type', function() {
        applyStoreTypeVisibility($(this).val());
        applyBlockPickerStoreFilter($(this).val());
    });


    function applyBlockPickerStoreFilter(storeType) {
        var isSalon     = (storeType === 'salon');
        var isHs        = (storeType === 'home_services');
        var salonRetail = false;
        var hsRetail    = false;
        
        var hasShipping = (storeType === 'physical_goods' || storeType === 'mixed');
        var hasBooking  = (storeType === 'services'       || storeType === 'mixed' || isSalon || isHs);
        var hideEcom    = (isSalon && !salonRetail) || (isHs && !hsRetail);
        
        var shippingBlocks = ['shipping_bar'];
        var bookingBlocks  = ['booking'];
        var ecomBlocks     = ['products', 'bundle', 'cart', 'plans', 'checkout'];
        shippingBlocks.forEach(function(el) {
            $('[data-element="' + el + '"]').toggle(hasShipping);
        });
        bookingBlocks.forEach(function(el) {
            $('[data-element="' + el + '"]').toggle(hasBooking);
        });
        ecomBlocks.forEach(function(el) {
            $('[data-element="' + el + '"]').toggle(!hideEcom);
        });
        
        window.Impulse.storeType = storeType;
    }

    
    applyBlockPickerStoreFilter($('#settings-store-type').val() || window.Impulse.storeType);

    
    (function() {
        var $wrap   = $('#store-country-wrap');
        var $search = $('#store-country-search');
        var $list   = $('#store-country-list');
        var $filter = $('#store-country-filter');
        var $opts   = $('#store-country-options');
        var $hidden = $('#store-country-value');

        function openList() {
            $list.show();
            $search.attr('readonly', false).focus().select();
        }
        function closeList() {
            var cur = $hidden.val();
            var label = $opts.find('[data-code="' + cur + '"]').text() || '';
            $search.val(label).attr('readonly', true);
            $list.hide();
            $filter.val('');
            $opts.find('.store-country-opt').show();
        }

        $search.on('click', function(e) { e.stopPropagation(); openList(); });
        $filter.on('input', function() {
            var q = $(this).val().toLowerCase();
            $opts.find('.store-country-opt').each(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(q) !== -1);
            });
        });
        $filter.on('keydown', function(e) {
            if (e.key === 'Escape') { closeList(); }
            if (e.key === 'Enter') {
                var $vis = $opts.find('.store-country-opt:visible').first();
                if ($vis.length) $vis.trigger('click');
            }
        });
        $(document).on('click', '.store-country-opt', function(e) {
            e.stopPropagation();
            var code  = $(this).data('code');
            var label = $(this).text();
            $hidden.val(code).trigger('change');
            $search.val(label);
            $opts.find('.store-country-opt').css('background', '');
            $(this).css('background', '#3a3f44');
            $list.hide();
            $filter.val('');
            $opts.find('.store-country-opt').show();
            $search.attr('readonly', true);
        });
        $(document).on('click', function(e) {
            if (!$wrap.is(e.target) && $wrap.find(e.target).length === 0) {
                if ($list.is(':visible')) closeList();
            }
        });
        
        $(document).on('mouseenter', '.store-country-opt', function() {
            $(this).css('background', '#3a3f44');
        }).on('mouseleave', '.store-country-opt', function() {
            var cur = $hidden.val();
            if ($(this).data('code') !== cur) $(this).css('background', '');
        });
        
        $opts.get(0) && (function(el) {
            var s = document.createElement('style');
            s.textContent = '#store-country-options::-webkit-scrollbar{display:none}';
            document.head.appendChild(s);
        })();
    })();

    
    $(document).on('click', '.impulse-settings-collapse', function() {
        var $div = $(this);
        var targetId = $div.data('target');
        var $body = $('#' + targetId);
        if (!$body.length) return;
        if ($body.is(':visible')) {
            $body.slideUp(150);
            $div.removeClass('is-open');
        } else {
            $body.slideDown(150);
            $div.addClass('is-open');
        }
    });


    $(document).on('input', '#imgopt-quality', function() {
        $('#imgopt-quality-val').text($(this).val() + '%');
    });
    $(document).on('input', '#imgopt-webp-quality', function() {
        $('#imgopt-webp-quality-val').text($(this).val() + '%');
    });

    
    $(document).on('click', '#imglib-detail-optimize', function() {
        var id = $('#imglib-detail').data('id');
        if (!id) return;
        var btn = $(this);
        btn.prop('disabled', true).text('Saving copy…');
        $.post(ajaxurl, {
            action: 'instinctor_imglib_optimize_one',
            nonce: window.Impulse.adminNonce,
            id: id
        }, function(r) {
            btn.prop('disabled', false).text('Save Optimized Copy');
            if (r.success) {
                var d = r.data;
                if (d.status === 'already_optimal') {
                    if (typeof showImpulseToast === 'function') showImpulseToast('Already at minimum size');
                } else {
                    
                    if (typeof showImpulseToast === 'function') {
                        showImpulseToast('Copy saved · ' + formatBytes(d.saved) + ' smaller · original preserved');
                    }
                    
                    loadImages(true);
                }
            }
        }).fail(function() { btn.prop('disabled', false).text('Save Optimized Copy'); });
    });

    var imglibPage = 1;
    var imglibLoading = false;
    var imglibHasMore = true;
    var imglibFilter = 'all';
    var imglibSelected = {};
    var imglibInitialized = false;
    var imglibImages = {}; 

    

    function loadImages(reset) {
        if (imglibLoading) return;
        if (reset) {
            imglibPage = 1;
            imglibHasMore = true;
            $('#imglib-grid').empty();
            imglibImages = {};
        }
        if (!imglibHasMore) return;
        
        imglibLoading = true;
        $('#imglib-loading').show();
        $('#imglib-empty').hide();
        
        $.post(ajaxurl, {
            action: 'instinctor_imglib_get',
            nonce: window.Impulse.adminNonce,
            page: imglibPage,
            filter: imglibFilter
        }, function(r) {
            imglibLoading = false;
            $('#imglib-loading').hide();
            
            if (!r.success) return;
            var d = r.data;
            imglibHasMore = d.page < d.pages;
            imglibPage++;
            
            $('#imglib-count').text(d.total + ' images');


            if (d.quota && d.quota.cap > 0) {
                var q = d.quota, $q = $('#imglib-quota');
                if (!$q.length) { $q = $('<span id="imglib-quota" style="margin-left:8px"></span>').insertAfter('#imglib-count'); }
                $q.text(q.used + ' of ' + q.cap + ' photos used')
                  .css('color', q.used >= q.cap ? '#e0e0e0' : '#999');
            } else {
                $('#imglib-quota').remove();
            }

            if (d.images.length === 0 && d.page === 1) {
                $('#imglib-empty').show();
                return;
            }
            
            var $grid = $('#imglib-grid');
            d.images.forEach(function(img) {
                imglibImages[img.id] = img;
                var card = '<div class="imglib-card' + (imglibSelected[img.id] ? ' selected' : '') + '" data-id="' + img.id + '" style="position:relative;cursor:pointer;border-radius:3px;overflow:hidden;background:#2a2e33;border:2px solid transparent">' +
                    '<button type="button" class="imglib-card-del" data-id="' + img.id + '" title="Delete image"><svg viewBox="0 0 24 24" width="11" height="11" 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 style="aspect-ratio:1;overflow:hidden"><img src="' + (img.thumb || img.url) + '" loading="lazy" style="width:100%;height:100%;object-fit:cover;display:block"></div>' +
                    '<div class="imglib-card-caption" style="padding:4px 6px">' +
                        '<div style="font-size:11px;color:#999;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escapeHtml(img.title || img.filename) + '</div>' +
                        '<div style="font-size:11px;color:#555">' + img.width + '×' + img.height + ' · ' + formatBytes(img.size) + '</div>' +
                    '</div>' +
                    (img.parent_id ? '<div style="position:absolute;top:4px;right:4px;background:#3a3f44;border-radius:2px;padding:1px 4px;font-size:9px;color:#888;line-height:14px" title="Optimised derivative — original preserved">copy</div>' : (img.optimized ? '<div style="position:absolute;top:4px;right:4px;width:6px;height:6px;background:#e0e0e0;border-radius:50%" title="Optimized at upload"></div>' : '')) +
                '</div>';
                $grid.append(card);
            });
        }).fail(function() {
            imglibLoading = false;
            $('#imglib-loading').hide();
        });
    }

    
    $(document).on('scroll', '.impulse-images-scroll', function() {
        if (this.scrollTop + this.clientHeight >= this.scrollHeight - 100) {
            loadImages(false);
        }
    });

    
    $(document).on('scroll', '.impulse-library-media .impulse-scroll', function() {
        if (this.scrollTop + this.clientHeight >= this.scrollHeight - 100) {
            loadImages(false);
        }
    });

    
    $(document).on('click', '.imglib-filter', function() {
        var f = $(this).data('filter');
        if (f === imglibFilter) return;
        imglibFilter = f;
        $('.imglib-filter').css({background:'#2a2e33',color:'#999'});
        $(this).css({background:'#e0e0e0',color:'#1d2327'});
        loadImages(true);
    });

    
    $(document).on('click', '#imglib-grid, #imglib-grid ~ *, .impulse-images-scroll', function(e) {
        if ($(e.target).closest('.imglib-card').length) return; 
        imglibSelected = {};
        $('.imglib-card').removeClass('selected');
        updateImglibBulkToolbar();
        $('#imglib-detail').hide();
    });

    
    $(document).on('click', '.imglib-card', function(e) {
        
        if ($(e.target).closest('.imglib-card-del, .imglib-card-confirm').length) return;
        var id = $(this).data('id');

        if (e.shiftKey || e.ctrlKey || e.metaKey) {
            
            if (imglibSelected[id]) {
                delete imglibSelected[id];
                $(this).removeClass('selected');
            } else {
                imglibSelected[id] = true;
                $(this).addClass('selected');
            }
            updateImglibBulkToolbar();
            return;
        }
        
        
        $('.imglib-card').removeClass('selected');
        $(this).addClass('selected');
        imglibSelected = {};
        imglibSelected[id] = true;
        updateImglibBulkToolbar();
        
        
        var img = imglibImages[id];
        if (img) {
            showImageDetail(img);
        }
    });

    function showImageDetail(img) {
        $('#imglib-detail-title').val(img.title || '');
        $('#imglib-detail-alt').val(img.alt || '');
        $('#imglib-detail-filename').text(img.filename);
        $('#imglib-detail-dims').text(img.width + ' × ' + img.height);
        $('#imglib-detail-size').text(formatBytes(img.size));
        $('#imglib-detail-type').text(img.mime.replace('image/', '').toUpperCase());
        $('#imglib-detail').data('id', img.id).data('url', img.url).show();
    }

    
    function saveDetailMeta() {
        var id = $('#imglib-detail').data('id');
        if (!id) return;
        var title = $('#imglib-detail-title').val();
        var alt   = $('#imglib-detail-alt').val();
        $.post(ajaxurl, {
            action: 'instinctor_imglib_update',
            nonce: window.Impulse.adminNonce,
            id: id,
            title: title,
            alt: alt,
            caption: ''
        }, function(r) {
            if (r.success) {
                if (imglibImages[id]) {
                    imglibImages[id].title = title;
                    imglibImages[id].alt   = alt;
                }
                
                var label = title || (imglibImages[id] && imglibImages[id].filename) || '';
                $('.imglib-card[data-id="' + id + '"] div[style*="ellipsis"]').text(label);
            }
        });
    }
    $(document).on('blur', '#imglib-detail-title, #imglib-detail-alt', function() {
        saveDetailMeta();
    });

    
    $(document).on('click', '#imglib-detail-copy', function() {
        var url = $('#imglib-detail').data('url');
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url);
            $(this).text('Copied!');
            var self = this;
            setTimeout(function() { $(self).text('Copy URL'); }, 1500);
        }
    });


    
    function _clearDepthMapIfMatch(id) {
        var panelImgId = $('input[name="image_id"]').val();
        if (panelImgId && String(panelImgId) === String(id)) {
            $('input[name="depth_map"]').val('');
            
            var elType = $('.impulse-panel-right').data('element-type');
            if (elType === 'image' && typeof window.buildSettingsForm === 'function') {
                var existing = $('.impulse-panel-right').data('existing-settings') || {};
                existing.depth_map = '';
                $('.impulse-panel-right').data('existing-settings', existing);
                $('#impulse-settings-body').html(window.buildSettingsForm('image', existing, []));
            }
        }
    }

    
    $(document).on('click', '#imglib-detail-delete', function() {
        var id = $('#imglib-detail').data('id');
        $.post(ajaxurl, { action: 'instinctor_imglib_delete', nonce: window.Impulse.adminNonce, id: id }, function(r) {
            if (r.success) {
                _clearDepthMapIfMatch(id);
                $('.imglib-card[data-id="' + id + '"]').remove();
                delete imglibImages[id];
                delete imglibSelected[id];
                $('#imglib-detail').hide();
                updateImglibBulkToolbar();
                loadImgOptStats();
            }
        });
    });

    
    function updateImglibBulkToolbar() {
        var count = Object.keys(imglibSelected).length;
        if (count > 1) {
            $('#imglib-bulk-toolbar').css('display','flex');
            $('#imglib-selected-count').text(count + ' selected');
        } else {
            $('#imglib-bulk-toolbar').css('display','none');
        }
    }


    

    var _mediaHoverTimer  = null;
    var _mediaHoverActive = null; 

    function showMediaHover($card, e) {
        var id  = $card.data('id');
        var img = imglibImages[id];
        if (!img) return;

        var $hp = $('#impulse-hover-preview');
        $hp.removeClass('preview-graphic').addClass('preview-media');

        
        var actionsHtml =
            '<div class="impulse-media-hover-actions">' +
            '<button type="button" class="media-action-insert" data-id="' + id + '">Insert</button>' +
            '<button type="button" class="media-action-copy" data-url="' + escapeHtml(img.url) + '">Copy URL</button>' +
            '</div>';

        $hp.find('.preview-content').html('<img src="' + escapeHtml(img.url) + '" alt="">');
        $hp.find('.preview-label').text((img.title || img.filename || '') + ' · ' + img.width + '×' + img.height);

        
        $hp.find('.impulse-media-hover-actions').remove();
        $hp.append(actionsHtml);

        
        var panelEl = $card.closest('.impulse-panel-left')[0];
        var left  = panelEl ? panelEl.getBoundingClientRect().right + 8 : e.clientX + 20;
        var top   = e.clientY - 80;
        var wh    = $(window).height();
        var ph    = 260; 
        if (top + ph > wh - 10) top = Math.max(10, wh - ph - 10);
        if (top < 10) top = 10;

        $hp.css({ top: top, left: left, display: 'block' });
        _mediaHoverActive = id;
    }

    function hideMediaHover() {
        clearTimeout(_mediaHoverTimer);
        _mediaHoverActive = null;
        var $hp = $('#impulse-hover-preview');
        
        if ($hp.hasClass('preview-media')) {
            $hp.hide().removeClass('preview-media');
            $hp.find('.impulse-media-hover-actions').remove();
        }
    }

    
    $(document).on('mouseenter', '.impulse-library-media .imglib-card', function(e) {
        var $card = $(this);
        var ev    = e;
        _mediaHoverTimer = setTimeout(function() { showMediaHover($card, ev); }, 250);
    });

    var _mediaHideTimer = null;
    $(document).on('mouseleave', '.impulse-library-media .imglib-card', function() {
        clearTimeout(_mediaHoverTimer);

        

        
        clearTimeout(_mediaHideTimer);
        _mediaHideTimer = setTimeout(function() {
            if (!$('#impulse-hover-preview:hover').length) hideMediaHover();
        }, 450);
    });

    
    $(document).on('mouseenter', '#impulse-hover-preview.preview-media', function() {
        clearTimeout(_mediaHoverTimer);
        clearTimeout(_mediaHideTimer);
    });
    $(document).on('mouseleave', '#impulse-hover-preview.preview-media', function() {
        hideMediaHover();
    });

    
    $(document).on('click', '.media-action-insert', function(e) {
        e.stopPropagation();
        var id  = $(this).data('id');
        var img = imglibImages[id];
        if (!img) return;
        
        if (typeof window._impulseImagePickerCallback === 'function') {
            window._impulseImagePickerCallback(img.url, img);
            window._impulseImagePickerCallback = null;
        } else if (typeof window.impulseInsertImage === 'function') {
            window.impulseInsertImage(img.url);
        } else {
            
            if (navigator.clipboard) navigator.clipboard.writeText(img.url);
            if (typeof showImpulseToast === 'function') showImpulseToast('URL copied — paste into image field');
        }
        hideMediaHover();
    });

    
    $(document).on('click', '.media-action-copy', function(e) {
        e.stopPropagation();
        var url = $(this).data('url');
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url);
            $(this).text('Copied!');
            var $btn = $(this);
            setTimeout(function() { $btn.text('Copy URL'); }, 1500);
        }
    });


    
    $(document).on('click', '.imglib-card-del', function(e) {
        e.stopPropagation();
        var $card = $(this).closest('.imglib-card');
        $('.imglib-card-confirm').remove();          
        var id = $(this).data('id');
        $card.append('<div class="imglib-card-confirm"><button type="button" class="imglib-card-confirm-yes" data-id="' + id + '">Delete</button></div>');
    });
    $(document).on('click', '.imglib-card-confirm-yes', function(e) {
        e.stopPropagation();
        var id = $(this).data('id');
        var $card = $(this).closest('.imglib-card');
        $.post(ajaxurl, { action: 'instinctor_imglib_delete', nonce: window.Impulse.adminNonce, id: id }, function(r) {
            if (r.success) {
                _clearDepthMapIfMatch(id);
                $card.remove();
                delete imglibImages[id];
                delete imglibSelected[id];
                $('#imglib-detail').hide();
                updateImglibBulkToolbar();
                if (typeof loadImgOptStats === 'function') loadImgOptStats();
            }
        });
    });
    
    $(document).on('click', '.imglib-card-confirm', function(e) {
        if ($(e.target).closest('.imglib-card-confirm-yes').length) return;
        e.stopPropagation();
        $(this).remove();
    });
    
    $(document).on('click', function(e) {
        if ($(e.target).closest('.imglib-card-confirm, .imglib-card-del').length) return;
        $('.imglib-card-confirm').remove();
    });

    
    $(document).on('click', '#imglib-deselect', function() {
        imglibSelected = {};
        $('.imglib-card').removeClass('selected');
        updateImglibBulkToolbar();
        $('#imglib-detail').hide();
    });

    
    $(document).on('click', '#imglib-bulk-delete', function() {
        var ids = Object.keys(imglibSelected);
        if (!ids.length) return;
        var btn = $(this);
        btn.prop('disabled', true).text('Deleting...');
        var remaining = ids.length;
        ids.forEach(function(id) {
            $.post(ajaxurl, { action: 'instinctor_imglib_delete', nonce: window.Impulse.adminNonce, id: id }, function() {
                $('.imglib-card[data-id="' + id + '"]').remove();
                delete imglibImages[id];
                remaining--;
                if (remaining === 0) {
                    imglibSelected = {};
                    updateImglibBulkToolbar();
                    $('#imglib-detail').hide();
                    loadImgOptStats();
                    btn.prop('disabled', false).text('Delete');
                    if (typeof showToast === 'function') window.showToast(ids.length + ' images deleted');
                }
            });
        });
    });

    
    $(document).on('click', '#imglib-bulk-optimize', function() {
        var ids = Object.keys(imglibSelected);
        if (!ids.length) return;
        var btn = $(this);
        btn.prop('disabled', true).text('Optimizing...');
        var remaining = ids.length;
        var savedTotal = 0;
        
        function optimizeNext(i) {
            if (i >= ids.length) {
                btn.prop('disabled', false).text('Optimize');
                loadImgOptStats();
                loadImages(true);
                if (typeof showToast === 'function') window.showToast(ids.length + ' images optimized, ' + formatBytes(savedTotal) + ' saved');
                return;
            }
            $.post(ajaxurl, {
                action: 'instinctor_imgopt_bulk',
                nonce: window.Impulse.adminNonce,
                batch_size: 1,
                attachment_id: ids[i]
            }, function(r) {
                if (r.success && r.data.results) {
                    r.data.results.forEach(function(res) { savedTotal += res.saved || 0; });
                }
                optimizeNext(i + 1);
            }).fail(function() {
                optimizeNext(i + 1);
            });
        }
        optimizeNext(0);
    });

    
    $(document).on('click', '#imglib-upload', function() {
        var $input = $('<input type="file" accept="image/*" multiple style="display:none">');
        $('body').append($input);
        $input.trigger('click');
        $input.on('change', function() {
            var files = Array.from(this.files);
            if (!files.length) { $input.remove(); return; }
            var remaining = files.length;
            files.forEach(function(file) {
                var fd = new FormData();
                fd.append('action', 'instinctor_imglib_upload');
                fd.append('nonce', window.Impulse.adminNonce);
                fd.append('image', file);
                $.ajax({
                    url: ajaxurl, type: 'POST', data: fd,
                    processData: false, contentType: false,
                    success: function() {
                        remaining--;
                        if (remaining === 0) { loadImages(true); loadImgOptStats(); }
                    },
                    error: function() {
                        remaining--;
                        if (remaining === 0) { loadImages(true); loadImgOptStats(); }
                    }
                });
            });
            $input.remove();
        });
    });

    function escapeHtml(t) {
        if (!t) return '';
        var d = document.createElement('div');
        d.textContent = t;
        return d.innerHTML;
    }


    (function suppressAutofill() {
        function stampInputs(root) {
            (root || document).querySelectorAll('input[type="text"], input[type="search"], input[type="email"]').forEach(function(el) {
                if (el.hasAttribute('data-autofill-stamped')) return;
                el.setAttribute('autocomplete', 'nope');
                el.setAttribute('data-form-type', 'other');
                el.setAttribute('data-lpignore', 'true');
                el.setAttribute('data-1p-ignore', 'true');
                
                if (!el.readOnly && !el.dataset.noReadonlyTrick) {
                    el.readOnly = true;
                    el.addEventListener('focus', function() { this.readOnly = false; }, { once: true });
                }
                el.setAttribute('data-autofill-stamped', '1');
            });
        }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() { stampInputs(); });
        } else {
            stampInputs();
        }
        var mo = new MutationObserver(function(mutations) {
            mutations.forEach(function(m) {
                m.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) stampInputs(node);
                });
            });
        });
        if (document.body) {
            mo.observe(document.body, { childList: true, subtree: true });
        }
    })();


    

    (function($) {
        'use strict';
        window.openImglibPicker = function(opts, callback) {
            if (window.openLibraryPick) return window.openLibraryPick(opts, callback);
        };
        window.closePicker = function() {};
    })(jQuery);


    

    var _icsOpenDropdown = null;

    function icsInit(container) {
        var $root = container ? $(container) : $(document);
        $root.find('select').not('.ics-initialized').each(function() {
            var $sel = $(this);
            
            if ($sel.closest('.impulse-canvas, .mce-container, #impulse-preview-frame').length) return;
            $sel.addClass('ics-initialized');

            
            var inlineStyle = $sel.attr('style') || '';
            var sizingClass = '';
            if (/flex\s*:\s*1/.test(inlineStyle) || /flex\s*:\s*1/.test(inlineStyle)) sizingClass = 'ics-flex1';
            else if (/width\s*:\s*100%/.test(inlineStyle)) sizingClass = 'ics-full';

            
            var $wrap = $('<div class="impulse-custom-select ' + sizingClass + '"></div>');
            var $val  = $('<div class="impulse-custom-select-value"></div>');
            var $arr  = $('<div class="impulse-custom-select-arrow"><svg viewBox="0 0 24 24" width="10" height="10" stroke="currentColor" fill="none" stroke-width="2.5"><polyline points="6 9 12 15 18 9"/></svg></div>');

            $wrap.append($val).append($arr);

            
            $sel.css({ position:'absolute', opacity:0, pointerEvents:'none', width:'1px', height:'1px', overflow:'hidden' });

            
            $sel.before($wrap);
            $wrap.append($sel); 

            
            function syncLabel() {
                var selected = $sel.find('option:selected');
                $val.text(selected.length ? selected.text() : '');
            }
            syncLabel();

            
            $wrap.on('click', function(e) {
                e.stopPropagation();
                if ($wrap.hasClass('ics-disabled')) return;

                
                if (_icsOpenDropdown && _icsOpenDropdown[0] !== $wrap[0]) {
                    icsClose(_icsOpenDropdown);
                }

                if ($wrap.hasClass('ics-open')) {
                    icsClose($wrap);
                    return;
                }


                
                
                var _selCls = ($sel.attr('class') || '').split(/\s+/).filter(function(c) {
                    return c && c !== 'ics-initialized';
                }).join(' ');
                var $drop = $('<div class="impulse-custom-select-dropdown ' + _selCls + '"></div>');
                $sel.find('option').each(function() {
                    var $opt = $(this);
                    var cls  = 'impulse-custom-select-option';
                    if ($opt.is(':selected'))  cls += ' ics-selected';
                    if ($opt.is(':disabled'))  cls += ' ics-disabled';
                    var $item = $('<div class="' + cls + '" data-value="' + $opt.val() + '">' + $opt.text() + '</div>');
                    $item.on('click', function(ev) {
                        ev.stopPropagation();
                        $sel.val($opt.val());
                        syncLabel();

                        

                        
                        icsClose($wrap);
                        $sel.trigger('change');
                    });
                    $drop.append($item);
                });

                
                var rect = $wrap[0].getBoundingClientRect();
                var dropWidth = Math.max(rect.width, 140);
                $drop.css({
                    top:   rect.bottom + window.scrollY,
                    left:  rect.left + window.scrollX,
                    width: dropWidth
                });

                
                $(document.body).append($drop);
                var dropH = $drop.outerHeight();
                var viewH = window.innerHeight;
                if (rect.bottom + dropH > viewH - 8) {
                    $drop.css('top', rect.top + window.scrollY - dropH);
                }

                $wrap.addClass('ics-open').data('ics-drop', $drop);
                _icsOpenDropdown = $wrap;
            });

            
            $sel.on('change', function() { syncLabel(); });

        });
    }

    function icsClose($wrap) {
        var $drop = $wrap.data('ics-drop');
        if ($drop) { $drop.remove(); $wrap.removeData('ics-drop'); }
        $wrap.removeClass('ics-open');
        if (_icsOpenDropdown && _icsOpenDropdown[0] === $wrap[0]) _icsOpenDropdown = null;
    }


    

    $(document).on('click', function() {
        if (_icsOpenDropdown) icsClose(_icsOpenDropdown);
    });
    function _icsAttachIframeCloser() {
        var iframe = document.getElementById('impulse-iframe');
        if (!iframe) return;
        var bind = function() {
            try {
                var d = iframe.contentDocument;
                if (!d || d.__icsCloserBound) return;
                d.addEventListener('click', function() {
                    if (_icsOpenDropdown) icsClose(_icsOpenDropdown);
                }, true);
                d.__icsCloserBound = true;
            } catch(_) {}
        };
        bind();
        iframe.addEventListener('load', bind);
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', _icsAttachIframeCloser);
    } else {
        _icsAttachIframeCloser();
    }

    
    $(window).on('scroll resize', function() {
        if (_icsOpenDropdown) icsClose(_icsOpenDropdown);
    });

    
    $(document).ready(function() {
        icsInit();
        
        window.positionWorkspaceTrack();
        $(window).on('resize', window.positionWorkspaceTrack);
    });

    
    (function() {
        var body = document.getElementById('impulse-settings-body');
        if (!body) return;
        var obs = new MutationObserver(function(mutations) {
            var hasChildChange = mutations.some(function(m) { return m.type === 'childList' && m.addedNodes.length; });
            if (!hasChildChange) return;
        });
        obs.observe(body, { childList: true });
    })();

    
    (function() {
        var _icsObserver = new MutationObserver(function(mutations) {
            var needsInit = false;
            mutations.forEach(function(m) {
                m.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if (node.tagName === 'SELECT' || $(node).find('select').length) needsInit = true;
                    }
                });
            });
            if (needsInit) icsInit();
        });
        if (document.body) {
            _icsObserver.observe(document.body, { childList: true, subtree: true });
        }
    })();

})(jQuery);
