/* SmartProductSEO Media Cleanup Admin JS Version 1.1.6 */
jQuery(function ($) {
    'use strict';

    var smcmlcObject = window.smcmlcAdmin || {};


    function smcText(key, fallback) {
        if (smcmlcObject && typeof smcmlcObject[key] !== 'undefined') {
            return smcmlcObject[key];
        }
        return fallback;
    }

    function smcNotice(message, type) {
        var safeMessage = $('<div>').text(message || '').html();
        var notice = $('<div class="smcmlc_floating-notice ' + (type || 'success') + '">' + safeMessage + '</div>');

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

        setTimeout(function () {
            notice.fadeOut(300, function () {
                notice.remove();
            });
        }, 2600);
    }

    function smcGetResponseMessage(response, fallback) {
        if (!response || typeof response.data === 'undefined') {
            return fallback;
        }

        if (typeof response.data === 'string') {
            return response.data;
        }

        if (response.data && typeof response.data.message !== 'undefined') {
            return response.data.message;
        }

        return fallback;
    }

    function smcCanRunAjax() {
        return smcmlcObject && smcmlcObject.ajaxUrl && smcmlcObject.nonce;
    }


    function smcParseSizeToBytes(sizeText) {
        var match;
        var value;
        var unit;
        var units = {
            b: 1,
            kb: 1024,
            mb: 1024 * 1024,
            gb: 1024 * 1024 * 1024,
            tb: 1024 * 1024 * 1024 * 1024
        };

        sizeText = $.trim(String(sizeText || '')).toLowerCase();

        if (!sizeText || sizeText.indexOf('missing') !== -1) {
            return 0;
        }

        match = sizeText.match(/([0-9]+(?:\.[0-9]+)?)\s*(b|kb|mb|gb|tb)/i);

        if (!match) {
            return 0;
        }

        value = parseFloat(match[1]);
        unit = String(match[2] || 'b').toLowerCase();

        if (isNaN(value) || typeof units[unit] === 'undefined') {
            return 0;
        }

        return Math.round(value * units[unit]);
    }

    function smcFormatBytes(bytes) {
        var units = ['B', 'KB', 'MB', 'GB', 'TB'];
        var index = 0;

        bytes = parseInt(bytes, 10) || 0;

        while (bytes >= 1024 && index < units.length - 1) {
            bytes = bytes / 1024;
            index++;
        }

        if (index === 0) {
            return bytes + ' ' + units[index];
        }

        return bytes.toFixed(bytes >= 10 ? 1 : 2).replace(/\.0$/, '') + ' ' + units[index];
    }

    function smcGetRowSizeBytes(row) {
        var explicit = parseInt(row.data('size-bytes'), 10);
        var sizeCell;

        if (explicit > 0) {
            return explicit;
        }

        sizeCell = row.find('.smcmlc_size-col, .smcmlc_file-size-col, [data-smcmlc_column="size"]').first();

        if (sizeCell.length) {
            return smcParseSizeToBytes(sizeCell.text());
        }

        return smcParseSizeToBytes(row.find('td').eq(7).text());
    }

    function smcGetImageCheckboxes() {
        return $('.smcmlc_scan-table tbody input[type="checkbox"], input.smcmlc_image-checkbox, input.smcmlc_image-select')
            .not('#smcmlc_select-all-images')
            .not('.smcmlc_select-all-images')
            .not('.smcmlc_select-all')
            .not('.smcmlc_bulk-select-all')
            .not('.smcmlc_select-all-images-control')
            .filter(function () {
                var checkbox = $(this);
                var value = parseInt(checkbox.val(), 10);
                var dataId = parseInt(checkbox.data('id'), 10);
                var attachmentId = parseInt(checkbox.data('attachment-id'), 10);

                return value > 0 || dataId > 0 || attachmentId > 0;
            });
    }

    function smcGetSelectAllBoxes() {
        return $('#smcmlc_select-all-images, .smcmlc_select-all-images, .smcmlc_select-all, .smcmlc_bulk-select-all, .smcmlc_select-all-images-control, [data-smcmlc_select-all="images"]')
            .filter('input[type="checkbox"]');
    }

    function smcGetSelectedImageIds() {
        var ids = [];

        smcGetImageCheckboxes().filter(':checked').each(function () {
            var checkbox = $(this);
            var id = parseInt(checkbox.val(), 10);

            if (!id) {
                id = parseInt(checkbox.data('id'), 10);
            }

            if (!id) {
                id = parseInt(checkbox.data('attachment-id'), 10);
            }

            if (id > 0 && $.inArray(id, ids) === -1) {
                ids.push(id);
            }
        });

        return ids;
    }

    function smcGetSelectedImageBytes() {
        var totalBytes = 0;

        smcGetImageCheckboxes().filter(':checked').each(function () {
            totalBytes += smcGetRowSizeBytes($(this).closest('tr'));
        });

        return totalBytes;
    }

    function smcEnsureStickyBulkBar() {
        if (!$('#smcmlc_scan-results').length || $('#smcmlc_sticky-bulk-bar').length) {
            return;
        }

        var bar = '';
        bar += '<div id="smcmlc_sticky-bulk-bar" class="smcmlc_sticky-bulk-bar" aria-live="polite">';
        bar += '<div class="smcmlc_sticky-bulk-inner">';
        bar += '<span class="smcmlc_sticky-selected"><strong id="smcmlc_sticky-selected-count">0</strong> image(s) selected</span>';
        bar += '<button type="button" class="smcmlc_btn smcmlc_btn-pink smcmlc_bulk-trash-selected smcmlc_sticky-bulk-trash">Move Selected to Trash</button>';
        bar += '</div>';
        bar += '</div>';

        $('body').append(bar);
    }

    function smcDecorateScanRows() {
        $('.smcmlc_scan-table tbody tr').each(function () {
            var row = $(this);
            var statusText = $.trim(row.find('.smcmlc_badge').first().text()).toLowerCase();
            var usageItems = row.find(
                '.smcmlc_woo-usage-item, .smcmlc_theme-usage-item, .smcmlc_theme-option-usage-item, ' +
                '.smcmlc_header-logo-usage-item, .smcmlc_footer-logo-usage-item, .smcmlc_option-usage-item, ' +
                '.smcmlc_content-usage-item, .smcmlc_usage-location-item, .smcmlc_used-in-item'
            ).not('.smcmlc_file-health-item');
            var usedInText = $.trim(usageItems.text());

            row.removeClass('smcmlc_protected-row smcmlc_likely-used-row smcmlc_content-detected-row smcmlc_cleanup-candidate-row smcmlc_review-row smcmlc_missing-file-row smcmlc_broken-image-row smcmlc_theme-protected-row smcmlc_woo-protected-row smcmlc_category-protected-row');

            if (row.find('.smcmlc_theme-usage-item, .smcmlc_theme-option-usage-item, .smcmlc_header-logo-usage-item, .smcmlc_footer-logo-usage-item, .smcmlc_used-in-theme-logo, .smcmlc_used-in-header-logo, .smcmlc_used-in-footer-logo, .smcmlc_used-in-theme-option').length) {
                row.addClass('smcmlc_theme-protected-row');
            }

            if (row.find('.smcmlc_woo-usage-item').length) {
                row.addClass('smcmlc_woo-protected-row');
            }

            if (usedInText.toLowerCase().indexOf('category') !== -1 || usedInText.toLowerCase().indexOf('term') !== -1) {
                row.addClass('smcmlc_category-protected-row');
            }

            if (statusText.indexOf('missing') !== -1) {
                row.addClass('smcmlc_missing-file-row');
            } else if (statusText.indexOf('broken') !== -1) {
                row.addClass('smcmlc_broken-image-row');
            } else if (statusText.indexOf('protected') !== -1) {
                row.addClass('smcmlc_protected-row');
            } else if (statusText.indexOf('likely used') !== -1 || usedInText.length > 0) {
                row.addClass('smcmlc_likely-used-row smcmlc_content-detected-row');
            } else if (statusText.indexOf('cleanup candidate') !== -1 || statusText.indexOf('unattached') !== -1) {
                row.addClass('smcmlc_cleanup-candidate-row');
            } else {
                row.addClass('smcmlc_review-row');
            }
        });
    }

    function smcEnhanceScanRowMetadata() {
        $('.smcmlc_scan-table tbody tr').each(function () {
            var row = $(this);
            var sizeCell = row.find('td').eq(7);
            var bytes = smcGetRowSizeBytes(row);

            if (!row.attr('data-size-bytes') && bytes > 0) {
                row.attr('data-size-bytes', bytes);
            }

            row.find('.smcmlc_trash-image').attr('title', 'Move this image to Trash first. You can restore it from Trash Review.');
            row.find('.smcmlc_delete-permanent').attr('title', 'Permanent deletion cannot be undone.');

            if (sizeCell.length && !sizeCell.attr('data-smcmlc_size-label')) {
                sizeCell.attr('data-smcmlc_size-label', $.trim(sizeCell.text()));
            }
        });
    }

    function smcEnhanceUsedByCounters() {
        $('.smcmlc_scan-table tbody tr').each(function () {
            var row = $(this);
            var usedInCell = row.find('td').eq(5);
            var usageItems = usedInCell.find(
                '.smcmlc_woo-usage-item, .smcmlc_used-in-item, .smcmlc_theme-usage-item, .smcmlc_theme-option-usage-item, ' +
                '.smcmlc_header-logo-usage-item, .smcmlc_footer-logo-usage-item, .smcmlc_option-usage-item, ' +
                '.smcmlc_content-usage-item, .smcmlc_usage-location-item'
            ).not('.smcmlc_file-health-item');
            var usageCount = usageItems.length;
            var labelTemplate = usageCount === 1
                ? smcText('usedByLocationText', 'Used By: %s Location')
                : smcText('usedByLocationsText', 'Used By: %s Locations');
            var labelText = String(labelTemplate).replace('%s', usageCount);

            usedInCell.find('.smcmlc_used-by-counter-js').remove();

            if (usageCount > 0) {
                usedInCell.prepend('<div class="smcmlc_used-by-counter smcmlc_used-by-counter-js">' + $('<div>').text(labelText).html() + '</div>');
            }
        });
    }

    function smcUpdateStorageAnalyticsSnapshot() {
        var rows = $('.smcmlc_scan-table tbody tr');
        var totalBytes = 0;
        var cleanupBytes = 0;
        var reviewBytes = 0;
        var protectedBytes = 0;

        rows.each(function () {
            var row = $(this);
            var statusText = $.trim(row.find('.smcmlc_badge').first().text()).toLowerCase();
            var bytes = smcGetRowSizeBytes(row);

            totalBytes += bytes;

            if (statusText.indexOf('cleanup candidate') !== -1 || statusText.indexOf('unattached') !== -1) {
                cleanupBytes += bytes;
            } else if (statusText.indexOf('protected') !== -1 || statusText.indexOf('likely used') !== -1) {
                protectedBytes += bytes;
            } else {
                reviewBytes += bytes;
            }
        });

        $('[data-smcmlc_analytics="total-size"]').text(smcFormatBytes(totalBytes));
        $('[data-smcmlc_analytics="cleanup-size"]').text(smcFormatBytes(cleanupBytes));
        $('[data-smcmlc_analytics="review-size"]').text(smcFormatBytes(reviewBytes));
        $('[data-smcmlc_analytics="protected-size"]').text(smcFormatBytes(protectedBytes));
    }

    function smcRemoveTrashMediaDetailsLinks() {
        $('.smcmlc_trash-table .smcmlc_file-actions').each(function () {
            var actions = $(this);
            var text = $.trim(actions.text()).toLowerCase();

            if (text.indexOf('media details') !== -1) {
                actions.remove();
            }
        });
    }

    function smcRefreshTrashEmptyState() {
        var table = $('.smcmlc_trash-table');

        if (!table.length) {
            return;
        }

        if (!smcGetTrashCheckboxes().length && !$('.smcmlc_trash-empty-message').length) {
            table.after('<p class="smcmlc_trash-empty-message">No trashed images found.</p>');
        }

        if (smcGetTrashCheckboxes().length) {
            $('.smcmlc_trash-empty-message').remove();
        }
    }

    function smcRefreshEnhancedDashboardUi() {
        if ($('.smcmlc_scan-table').length) {
            smcEnhanceScanRowMetadata();
            smcDecorateScanRows();
            smcEnhanceUsedByCounters();
            smcUpdateStorageAnalyticsSnapshot();
        }

        smcRemoveTrashMediaDetailsLinks();
    }

    function smcUpdateBulkButtonState() {
        var checkedCount = smcGetSelectedImageIds().length;
        var totalCount = smcGetImageCheckboxes().length;
        var bulkButton = $('#smcmlc_bulk-trash-selected, .smcmlc_bulk-trash-selected');
        var selectedCount = $('#smcmlc_selected-count, .smcmlc_selected-count, #smcmlc_bottom-selected-count, #smcmlc_sticky-selected-count');
        var stickyBar = $('#smcmlc_sticky-bulk-bar');
        var selectAllBoxes = smcGetSelectAllBoxes();

        if (selectedCount.length) {
            selectedCount.text(checkedCount);
        }

        $('.smcmlc_selected-storage-count, [data-smcmlc_selected-storage]').text(smcFormatBytes(smcGetSelectedImageBytes()));

        if (bulkButton.length) {
            bulkButton.prop('disabled', checkedCount < 1);
        }

        if (stickyBar.length) {
            stickyBar.toggleClass('smcmlc_sticky-bulk-visible', checkedCount > 0);
        }

        selectAllBoxes.prop('checked', totalCount > 0 && checkedCount === totalCount);
        selectAllBoxes.prop('indeterminate', checkedCount > 0 && checkedCount < totalCount);
    }

    function smcResetSelectAll() {
        smcGetSelectAllBoxes().prop('checked', false).prop('indeterminate', false);
        smcGetImageCheckboxes().prop('checked', false);
        smcUpdateBulkButtonState();
    }

    function smcRemoveRowById(id) {
        $('[data-smcmlc_row-id="' + id + '"], [data-attachment-id="' + id + '"]').fadeOut(250, function () {
            $(this).remove();
            smcUpdateBulkButtonState();
            smcUpdateStorageAnalyticsSnapshot();
            smcRefreshTrashEmptyState();
        });
    }

    function smcAfterScanLoaded(response) {
        if (!response || !response.data || typeof response.data.html === 'undefined') {
            return;
        }

        $('#smcmlc_scan-results').first().html(response.data.html);
        smcEnsureStickyBulkBar();
        smcRefreshEnhancedDashboardUi();
        smcResetSelectAll();

        if (response.data.summary && typeof response.data.summary.total_size !== 'undefined') {
            $('#smcmlc_last-scan-size').text(response.data.summary.total_size);
        }
    }

    function smcRunBulkTrash(button) {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        var ids = smcGetSelectedImageIds();

        if (!ids.length) {
            smcNotice(smcText('noImagesSelectedText', 'Please select at least one image first.'), 'error');
            return;
        }

        if (!confirm(smcText('confirmBulkTrash', 'Move selected image(s) to Trash? You can restore them from the Trash Review page.') + '\n\nSelected: ' + ids.length)) {
            return;
        }

        button.prop('disabled', true).text(smcText('bulkTrashRunningText', 'Moving selected images...'));

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_bulk_trash_images',
            nonce: smcmlcObject.nonce,
            ids: ids
        }).done(function (response) {
            if (response.success) {
                var trashedIds = [];

                if (response.data && $.isArray(response.data.trashed_ids)) {
                    trashedIds = response.data.trashed_ids;
                } else if (response.data && $.isArray(response.data.trashed)) {
                    trashedIds = response.data.trashed;
                }

                if (trashedIds.length) {
                    $.each(trashedIds, function (index, id) {
                        smcRemoveRowById(id);
                    });
                } else {
                    smcGetImageCheckboxes().filter(':checked').each(function () {
                        $(this).closest('tr').fadeOut(250, function () {
                            $(this).remove();
                            smcUpdateBulkButtonState();
                            smcUpdateStorageAnalyticsSnapshot();
                        });
                    });
                }

                smcGetSelectAllBoxes().prop('checked', false).prop('indeterminate', false);
                smcNotice(smcGetResponseMessage(response, smcText('bulkTrashSuccessText', 'Selected image(s) moved to Trash.')), 'success');
            } else {
                smcNotice(smcGetResponseMessage(response, smcText('bulkTrashErrorText', 'Could not move selected images to Trash.')), 'error');
            }
        }).fail(function () {
            smcNotice('Could not move selected images to Trash. Please try again.', 'error');
        }).always(function () {
            button.prop('disabled', false).text(smcText('bulkTrashText', 'Move Selected to Trash'));
            smcUpdateBulkButtonState();
        });
    }

    $(document).on('click', '#smcmlc_run-scan', function () {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        var button = $(this);
        var originalText = button.text();
        button.prop('disabled', true).text(smcText('scanningText', 'Scanning...'));

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_scan_media_library',
            nonce: smcmlcObject.nonce
        }).done(function (response) {
            if (response.success) {
                smcAfterScanLoaded(response);
                smcNotice('Scan complete. ' + response.data.count + ' images found.', 'success');
            } else {
                smcNotice(smcGetResponseMessage(response, 'Scan failed.'), 'error');
            }
        }).fail(function () {
            smcNotice('Scan failed. Please refresh and try again.', 'error');
        }).always(function () {
            button.prop('disabled', false).text(originalText || smcText('scanButtonText', 'Scan Media Library'));
        });
    });

    $(document).on('change', '#smcmlc_select-all-images, .smcmlc_select-all-images, .smcmlc_select-all, .smcmlc_bulk-select-all, .smcmlc_select-all-images-control, [data-smcmlc_select-all="images"]', function () {
        var shouldCheck = $(this).is(':checked');

        smcGetImageCheckboxes().prop('checked', shouldCheck);
        smcGetSelectAllBoxes().prop('checked', shouldCheck).prop('indeterminate', false);
        smcUpdateBulkButtonState();
    });

    $(document).on('change', '.smcmlc_image-checkbox, .smcmlc_image-select, .smcmlc_scan-table tbody input[type="checkbox"]', function () {
        if ($(this).is('#smcmlc_select-all-images, .smcmlc_select-all-images, .smcmlc_select-all, .smcmlc_bulk-select-all, .smcmlc_select-all-images-control, [data-smcmlc_select-all="images"]')) {
            return;
        }

        smcUpdateBulkButtonState();
    });

    $(document).on('click', '.smcmlc_trash-image, .smcmlc_trash-image', function () {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        if (!confirm(smcText('confirmTrash', 'Move selected image(s) to Trash? You can restore them from the Trash Review page.'))) {
            return;
        }

        var button = $(this);
        var id = button.data('id');

        button.prop('disabled', true).text('Trashing...');

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_trash_image',
            nonce: smcmlcObject.nonce,
            id: id
        }).done(function (response) {
            if (response.success) {
                smcRemoveRowById(id);
                smcNotice(smcGetResponseMessage(response, 'Image moved to Trash.'), 'success');
            } else {
                button.prop('disabled', false).text('Move to Trash');
                smcNotice(smcGetResponseMessage(response, 'Could not trash image.'), 'error');
            }
        }).fail(function () {
            button.prop('disabled', false).text('Move to Trash');
            smcNotice('Could not trash image. Please try again.', 'error');
        });
    });

    $(document).on('click', '#smcmlc_bulk-trash-selected, .smcmlc_bulk-trash-selected', function () {
        smcRunBulkTrash($(this));
    });

    $(document).on('click', '.smcmlc_restore-image, .smcmlc_restore-image', function () {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        var button = $(this);
        var id = button.data('id');

        button.prop('disabled', true).text('Restoring...');

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_restore_image',
            nonce: smcmlcObject.nonce,
            id: id
        }).done(function (response) {
            if (response.success) {
                smcRemoveRowById(id);
                smcNotice(smcGetResponseMessage(response, 'Image restored.'), 'success');
            } else {
                button.prop('disabled', false).text('Restore');
                smcNotice(smcGetResponseMessage(response, 'Could not restore image.'), 'error');
            }
        }).fail(function () {
            button.prop('disabled', false).text('Restore');
            smcNotice('Could not restore image. Please try again.', 'error');
        });
    });

    $(document).on('click', '.smcmlc_delete-permanent, .smcmlc_delete-permanent', function () {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        if (!confirm(smcText('confirmDelete', 'Permanent deletion cannot be undone. Please check the product/page first before deleting permanently.'))) {
            return;
        }

        var button = $(this);
        var id = button.data('id');

        button.prop('disabled', true).text('Deleting...');

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_delete_image_permanently',
            nonce: smcmlcObject.nonce,
            id: id
        }).done(function (response) {
            if (response.success) {
                smcRemoveRowById(id);
                smcNotice(smcGetResponseMessage(response, 'Image permanently deleted.'), 'success');
            } else {
                button.prop('disabled', false).text('Permanent Delete');
                smcNotice(smcGetResponseMessage(response, 'Could not delete image.'), 'error');
            }
        }).fail(function () {
            button.prop('disabled', false).text('Permanent Delete');
            smcNotice('Could not delete image. Please try again.', 'error');
        });
    });

    function smcGetTrashCheckboxes() {
        return $('.smcmlc_trash-table tbody input.smcmlc_trash-image-select, .smcmlc_trash-table tbody input.smcmlc_trash-image-checkbox, .smcmlc_trash-table tbody input.smcmlc_trash-image-select, .smcmlc_trash-table tbody input.smcmlc_trash-image-checkbox')
            .filter(function () {
                var value = parseInt($(this).val(), 10);
                return value > 0;
            });
    }

    function smcGetTrashSelectAllBoxes() {
        return $('.smcmlc_trash-select-all-control, .smcmlc_trash-select-all-control').filter('input[type="checkbox"]');
    }

    function smcGetSelectedTrashIds() {
        var ids = [];

        smcGetTrashCheckboxes().filter(':checked').each(function () {
            var id = parseInt($(this).val(), 10);

            if (id > 0 && $.inArray(id, ids) === -1) {
                ids.push(id);
            }
        });

        return ids;
    }

    function smcGetTrashRowSizeBytes(row) {
        var explicit = parseInt(row.data('size-bytes'), 10);
        var sizeCell;

        if (explicit > 0) {
            return explicit;
        }

        sizeCell = row.find('td').eq(6);

        if (!sizeCell.length || !$.trim(sizeCell.text())) {
            sizeCell = row.find('td').eq(row.find('td').length - 2);
        }

        return smcParseSizeToBytes(sizeCell.text());
    }

    function smcGetSelectedTrashBytes() {
        var totalBytes = 0;

        smcGetTrashCheckboxes().filter(':checked').each(function () {
            totalBytes += smcGetTrashRowSizeBytes($(this).closest('tr'));
        });

        return totalBytes;
    }

    function smcUpdateTrashBulkState() {
        var selectedIds = smcGetSelectedTrashIds();
        var checkedCount = selectedIds.length;
        var totalCount = smcGetTrashCheckboxes().length;
        var selectAllBoxes = smcGetTrashSelectAllBoxes();

        $('.smcmlc_trash-selected-count').text(checkedCount);
        $('.smcmlc_trash-selected-storage-count, [data-smcmlc_trash-selected-storage]').text(smcFormatBytes(smcGetSelectedTrashBytes()));
        $('.smcmlc_bulk-restore-selected, .smcmlc_bulk-delete-permanent').prop('disabled', checkedCount < 1);

        selectAllBoxes.prop('checked', totalCount > 0 && checkedCount === totalCount);
        selectAllBoxes.prop('indeterminate', checkedCount > 0 && checkedCount < totalCount);
        smcRemoveTrashMediaDetailsLinks();
        smcRefreshTrashEmptyState();
    }

    function smcRemoveTrashRowById(id) {
        $('[data-smcmlc_trash-row-id="' + id + '"], .smcmlc_trash-table [data-attachment-id="' + id + '"]').fadeOut(250, function () {
            $(this).remove();
            smcUpdateTrashBulkState();

            if (!smcGetTrashCheckboxes().length) {
                $('.smcmlc_trash-table').fadeOut(200);
            }
        });
    }

    function smcRunBulkTrashRestore(button) {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        var ids = smcGetSelectedTrashIds();

        if (!ids.length) {
            smcNotice(smcText('noImagesSelectedText', 'Please select at least one image first.'), 'error');
            return;
        }

        button.prop('disabled', true).text(smcText('bulkRestoreRunningText', 'Restoring selected...'));

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_bulk_restore_images',
            nonce: smcmlcObject.nonce,
            ids: ids
        }).done(function (response) {
            if (response.success) {
                var restoredIds = [];

                if (response.data && $.isArray(response.data.restored_ids)) {
                    restoredIds = response.data.restored_ids;
                }

                if (restoredIds.length) {
                    $.each(restoredIds, function (index, id) {
                        smcRemoveTrashRowById(id);
                    });
                } else {
                    smcGetTrashCheckboxes().filter(':checked').each(function () {
                        $(this).closest('tr').fadeOut(250, function () {
                            $(this).remove();
                            smcUpdateTrashBulkState();
                        });
                    });
                }

                smcGetTrashSelectAllBoxes().prop('checked', false).prop('indeterminate', false);
                smcNotice(smcGetResponseMessage(response, 'Selected image(s) restored.'), 'success');
            } else {
                smcNotice(smcGetResponseMessage(response, 'Could not restore selected image(s).'), 'error');
            }
        }).fail(function () {
            smcNotice('Could not restore selected image(s). Please try again.', 'error');
        }).always(function () {
            button.prop('disabled', false).text(smcText('bulkRestoreText', 'Restore Selected'));
            smcUpdateTrashBulkState();
        });
    }

    function smcRunBulkPermanentDelete(button) {
        if (!smcCanRunAjax()) {
            smcNotice('SmartProductSEO Media Cleanup admin connection is not ready. Please refresh and try again.', 'error');
            return;
        }

        var ids = smcGetSelectedTrashIds();

        if (!ids.length) {
            smcNotice(smcText('noImagesSelectedText', 'Please select at least one image first.'), 'error');
            return;
        }

        if (!confirm(smcText('confirmBulkDelete', 'Permanently delete selected image(s)? This cannot be undone.'))) {
            return;
        }

        button.prop('disabled', true).text(smcText('bulkPermanentDeleteRunningText', 'Deleting selected...'));

        $.post(smcmlcObject.ajaxUrl, {
            action: 'smcmlc_bulk_delete_images_permanently',
            nonce: smcmlcObject.nonce,
            ids: ids
        }).done(function (response) {
            if (response.success) {
                var deletedIds = [];

                if (response.data && $.isArray(response.data.deleted_ids)) {
                    deletedIds = response.data.deleted_ids;
                }

                if (deletedIds.length) {
                    $.each(deletedIds, function (index, id) {
                        smcRemoveTrashRowById(id);
                    });
                } else {
                    smcGetTrashCheckboxes().filter(':checked').each(function () {
                        $(this).closest('tr').fadeOut(250, function () {
                            $(this).remove();
                            smcUpdateTrashBulkState();
                        });
                    });
                }

                smcGetTrashSelectAllBoxes().prop('checked', false).prop('indeterminate', false);
                smcNotice(smcGetResponseMessage(response, 'Selected image(s) permanently deleted.'), 'success');
            } else {
                smcNotice(smcGetResponseMessage(response, 'Could not permanently delete selected image(s).'), 'error');
            }
        }).fail(function () {
            smcNotice('Could not permanently delete selected image(s). Please try again.', 'error');
        }).always(function () {
            button.prop('disabled', false).text(smcText('bulkPermanentDeleteText', 'Permanent Delete Selected'));
            smcUpdateTrashBulkState();
        });
    }

    $(document).on('change', '.smcmlc_trash-select-all-control', function () {
        var shouldCheck = $(this).is(':checked');

        smcGetTrashCheckboxes().prop('checked', shouldCheck);
        smcGetTrashSelectAllBoxes().prop('checked', shouldCheck).prop('indeterminate', false);
        smcUpdateTrashBulkState();
    });

    $(document).on('change', '.smcmlc_trash-image-select, .smcmlc_trash-image-checkbox', function () {
        smcUpdateTrashBulkState();
    });

    $(document).on('click', '.smcmlc_bulk-restore-selected', function () {
        smcRunBulkTrashRestore($(this));
    });

    $(document).on('click', '.smcmlc_bulk-delete-permanent', function () {
        smcRunBulkPermanentDelete($(this));
    });

    smcEnsureStickyBulkBar();
    smcRefreshEnhancedDashboardUi();
    smcUpdateBulkButtonState();
    smcUpdateTrashBulkState();
});