/**
 * Product Synchronization JavaScript
 *
 * Handles all JavaScript functionality for product synchronization.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/assets/js
 */

(function($) {
    $(document).ready(function() {
        
        // Handle single product sync
        $('.momcs-sync-product').on('click', function() {
            const button = $(this);
            const productId = button.data('product-id');
            const spinner = $('#momcs-sync-spinner-' + productId);
            const message = $('#momcs-sync-message-' + productId);
            
            // Disable button and show spinner
            button.prop('disabled', true);
            spinner.addClass('is-active');
            message.removeClass('success error').text('');
            
            // Sync product via AJAX
            $.ajax({
                url: momcs_sync.ajax_url,
                type: 'POST',
                data: {
                    action: 'momcs_sync_product',
                    nonce: momcs_sync.nonce,
                    product_id: productId
                },
                success: function(response) {
                    spinner.removeClass('is-active');
                    button.prop('disabled', false);
                    
                    if (response.success) {
                        message.addClass('success').text(momcs_sync.strings.sync_success);
                        
                        // Update sync status
                        const statusCell = button.closest('tr').find('.column-sync-status');
                        statusCell.html('<span class="momcs-sync-status synced">' + 
                            'Synced' + 
                            '<span class="momcs-sync-tooltip">' + 
                            'Amazon ID: ' + response.data.data.id + ', Last synced: ' + getCurrentDateTime() + 
                            '</span>' + 
                            '</span>');
                    } else {
                        message.addClass('error').text(response.data.message || momcs_sync.strings.sync_error);
                    }
                    
                    // Hide message after 3 seconds
                    setTimeout(function() {
                        message.removeClass('success error').text('');
                    }, 3000);
                },
                error: function() {
                    spinner.removeClass('is-active');
                    button.prop('disabled', false);
                    message.addClass('error').text(momcs_sync.strings.sync_error);
                    
                    // Hide message after 3 seconds
                    setTimeout(function() {
                        message.removeClass('success error').text('');
                    }, 3000);
                }
            });
        });
        
        // Handle bulk product sync
        $('#momcs-sync-bulk-sync').on('click', function() {
            const button = $(this);
            const spinner = $('#momcs-sync-bulk-spinner');
            const message = $('#momcs-sync-bulk-message');
            
            // Get selected product IDs
            const productIds = [];
            $('input[name="product_ids[]"]:checked').each(function() {
                productIds.push($(this).val());
            });
            
            // Check if any products are selected
            if (productIds.length === 0) {
                alert(momcs_sync.strings.no_products);
                return;
            }
            
            // Confirm bulk sync
            if (!confirm(momcs_sync.strings.confirm_bulk_sync)) {
                return;
            }
        
        // Disable button and show spinner
        button.prop('disabled', true);
        spinner.addClass('is-active');
        message.removeClass('success error').text('');
        
        // Sync products via AJAX
        $.ajax({
            url: momcs_sync.ajax_url,
            type: 'POST',
            data: {
                action: 'momcs_sync_products_bulk',
                nonce: momcs_sync.nonce,
                    product_ids: productIds
            },
            success: function(response) {
                spinner.removeClass('is-active');
                button.prop('disabled', false);
                
                if (response.success) {
                    message.addClass('success').text(momcs_sync.strings.bulk_sync_success);
                    
                    // Update sync status for successful syncs
                    if (response.data.success) {
                        $.each(response.data.success, function(productId, result) {
                            const statusCell = $('input[name="product_ids[]"][value="' + productId + '"]').closest('tr').find('.column-sync-status');
                            statusCell.html('<span class="momcs-sync-status synced">' + 
                                'Synced' + 
                                '<span class="momcs-sync-tooltip">' + 
                                'Amazon ID: ' + result.data.id + ', Last synced: ' + getCurrentDateTime() + 
                                '</span>' + 
                                '</span>');
                        });
                    }
                    
                    // Show failed syncs if any
                    if (response.data.failed && Object.keys(response.data.failed).length > 0) {
                        let failedMessage = 'Failed to sync ' + Object.keys(response.data.failed).length + ' products.';
                        message.removeClass('success').addClass('error').text(failedMessage);
                    }
                } else {
                    message.addClass('error').text(response.data.message || momcs_sync.strings.bulk_sync_error);
                }
                
                // Hide message after 5 seconds
                setTimeout(function() {
                    message.removeClass('success error').text('');
                }, 5000);
            },
            error: function() {
                spinner.removeClass('is-active');
                button.prop('disabled', false);
                message.addClass('error').text(momcs_sync.strings.bulk_sync_error);
                
                // Hide message after 5 seconds
                setTimeout(function() {
                    message.removeClass('success error').text('');
                }, 5000);
            }
        });
        });
        
        // Handle "Select All" checkboxes
        $('#cb-select-all-1, #cb-select-all-2').on('change', function() {
            const isChecked = $(this).prop('checked');
            $('input[name="product_ids[]"]').prop('checked', isChecked);
            
            // Sync the other "Select All" checkbox
            const id = $(this).attr('id');
            if (id === 'cb-select-all-1') {
                $('#cb-select-all-2').prop('checked', isChecked);
            } else {
                $('#cb-select-all-1').prop('checked', isChecked);
            }
        });

        /** Category pills expand/collapse */
        $(document).on('click keydown', '.momcs-category-pill-toggle', function(e) {
            if (e.type === 'keydown' && e.which !== 13 && e.which !== 32) {
                return;
            }
            e.preventDefault();

            var $pills = $(this).closest('.momcs-category-pills');
            var $toggle = $(this);

            if ($pills.hasClass('momcs-categories-expanded')) {
                $pills.removeClass('momcs-categories-expanded');
                var hiddenCount = $pills.find('.momcs-category-pill-hidden').length;
                $toggle.text('+' + hiddenCount);
                $toggle.attr('title', 'Click to show all categories');
            } else {
                $pills.addClass('momcs-categories-expanded');
                $toggle.html('&minus;');
                $toggle.attr('title', 'Click to hide extra categories');
            }
        });

        /**  Issues modal - modern UI like sync queue  */
        $(document).on('click', '.momcs-amz-issues-btn', function () {
            var pid = $(this).data('product-id');
            
            // Debug: Check if momcs_sync object is available
            if (typeof momcs_sync === 'undefined') {
                alert('AJAX configuration not loaded. Please refresh the page.');
                return;
            }
            
            // Show loading modal first (like sync queue)
            showIssuesLoadingModal(pid);            
            $.post(momcs_sync.ajax_url, {
                action: 'momcs_amz_get_listing_issues',
                nonce: momcs_sync.nonce,
                product_id: pid
            }, function (resp) {
                // Remove loading modal
                $('.momcs-sync-modal-overlay, .momcs-sync-loading-modal').remove();
                
                if (!resp.success) {
                    alert((resp.data && resp.data.message) ? resp.data.message : 'Error fetching issues');
                    return;
                }
                renderIssuesModal(pid, resp.data.issues);
            }).fail(function(xhr, status, error) {
                $('.momcs-sync-modal-overlay, .momcs-sync-loading-modal').remove();
                console.error('AJAX Error:', status, error);
                alert('Network error occurred while fetching issues');
            });
        });

        function showIssuesLoadingModal(productId) {
            const loadingHtml = '<div class="momcs-sync-modal-overlay"></div>' +
                '<div class="momcs-sync-loading-modal">' +
                '<div class="momcs-sync-spinner is-active"></div>' +
                '<p>Loading issues</p></div>';
            $('body').append(loadingHtml);
        }

        function renderIssuesModal(productId, data) {
            // Get product name from the table row for better UX
            const productRow = $('button[data-product-id="' + productId + '"]').closest('tr');
            const productName = productRow.find('.column-name a').text().trim() || ('Product #' + productId);
            
            // Build modern modal HTML like sync queue
            let html = '<div class="momcs-sync-modal-overlay"></div>';
            html += '<div class="momcs-sync-modal">' +
                '<div class="momcs-sync-modal-header">' +
                '<h2>Amazon Listing Issues \u2014 ' + escapeHtml(productName) + '</h2>' +
                '<div class="momcs-sync-modal-actions">' +
                '<button type="button" class="momcs-sync-modal-close" aria-label="Close">&times;</button>' +
                '</div>' +
                '</div>';

            // Content area
            html += '<div class="momcs-issues-content">';
            
            if ($.isEmptyObject(data) || ($.isEmptyObject(data.ERROR || []) && $.isEmptyObject(data.WARNING || []))) {
                html += '<div class="momcs-no-issues">' +
                    '<div class="momcs-sync-status-chip success">' +
                    '<span class="momcs-sync-status-dot"></span>' +
                    'No issues found' +
                    '</div>' +
                    '<p style="margin-top: 10px; color: #666;">This product has no reported issues.</p>' +
                    '</div>';
            } else {
                // Group issues by severity with modern styling
                $.each(['ERROR', 'WARNING'], function(index, severity) {
                    const issues = data[severity] || [];
                    if (issues.length > 0) {
                        const chipClass = severity === 'ERROR' ? 'error' : 'warning';
                        const severityLabel = severity === 'ERROR' ? 'Errors' : 'Warnings';
                        
                        html += '<div class="momcs-issues-section">' +
                            '<div class="momcs-issues-section-header">' +
                            '<div class="momcs-sync-status-chip ' + chipClass + '">' +
                            '<span class="momcs-sync-status-dot"></span>' +
                            severityLabel + ' (' + issues.length + ')' +
                            '</div>' +
                            '</div>';
                            
                        html += '<ul class="momcs-sync-timeline">';
                        $.each(issues, function(_, issue) {
                            const issueClass = 'momcs-sev-' + (severity === 'ERROR' ? 'error' : 'warning');
                            html += '<li class="momcs-sync-node ' + issueClass + '">' +
                                '<div class="momcs-issue-details">' +
                                '<strong>' + (issue.message || 'Unknown issue') + '</strong>';
                            if (issue.code) {
                                html += '<div class="momcs-issue-code">Code: <code>' + issue.code + '</code></div>';
                            }
                            html += '</div></li>';
                        });
                        html += '</ul></div>';
                    }
                });
            }
            
            html += '</div></div>';
            
            // Add to page
            $('body').append(html);
            
            // Add close functionality (one-time events to avoid duplication)
            $('.momcs-sync-modal-close').off('click').on('click', function() {
                $('.momcs-sync-modal-overlay, .momcs-sync-modal').remove();
            });
            $('.momcs-sync-modal-overlay').off('click').on('click', function(e) {
                if (e.target === this) {
                    $('.momcs-sync-modal-overlay, .momcs-sync-modal').remove();
                }
            });
        }

        // Handle refresh status button
        $('#momcs-amz-refresh-status').on('click', function() {
            const button = $(this);
            // Only target body cells, not header cells
            const statusColumns = $('tbody .column-status');
            const issuesColumns = $('tbody .column-issues');
            
            // Get all product IDs from current page
            const productIds = [];
            $('input[name="product_ids[]"]').each(function() {
                productIds.push($(this).val());
            });
            
            if (productIds.length === 0) {
                return;
            }
            
            // Start loading state
            button.addClass('is-loading').prop('disabled', true);
            
            // Add shimmer effect to body status and issues columns only
            statusColumns.addClass('momcs-shimmer-active');
            issuesColumns.addClass('momcs-shimmer-active');
            
            
            // Make AJAX call to refresh status
            $.ajax({
                url: momcs_sync.ajax_url,
                type: 'POST',
                data: {
                    action: 'momcs_amz_refresh_product_status',
                    nonce: momcs_sync.nonce,
                    product_ids: productIds
                },
                success: function(response) {
                    
                    if (response.success && response.data.results) {
                        // Update each product's status and issues progressively
                        $.each(response.data.results, function(productId, result) {
                            if (result.success) {
                                // Pass marketplace_statuses for Premium users
                                updateProductStatus(
                                    productId, 
                                    result.listing_status, 
                                    result.has_issues,
                                    result.marketplace_statuses || {}
                                );
                            }
                        });
                    }
                    
                    // Remove loading state and shimmer
                    finishRefresh(button, statusColumns, issuesColumns);
                },
                error: function(xhr, status, error) {
                    console.error('Error refreshing status:', error);
                    
                    // Remove loading state and shimmer even on error (keep old state)
                    finishRefresh(button, statusColumns, issuesColumns);
                }
            });
        });
        
        /**
         * Update product status display in the table row.
         * 
         * For Premium users with marketplace_statuses data, renders per-marketplace chips.
         * For Free users or when no marketplace data exists, renders legacy single-status chips.
         *
         * @param {string|number} productId        The product ID.
         * @param {string}        listingStatus    The listing status (uploaded, discoverable, processing, etc.).
         * @param {boolean}       hasIssues        Whether the product has listing issues.
         * @param {Object}        marketplaceStatuses Optional. Per-marketplace status data for Premium users.
         */
        function updateProductStatus(productId, listingStatus, hasIssues, marketplaceStatuses) {
            marketplaceStatuses = marketplaceStatuses || {};
            
            const productRow = $('input[name="product_ids[]"][value="' + productId + '"]').closest('tr');
            const statusColumn = productRow.find('.column-status');
            const issuesColumn = productRow.find('.column-issues');
            
            // Remove shimmer from this specific product first
            statusColumn.removeClass('momcs-shimmer-active');
            issuesColumn.removeClass('momcs-shimmer-active');
            
            // Determine status HTML based on plan and available data
            let statusHtml = '';
            
            // Check if we have marketplace data and are Premium
            if (momcs_sync.is_premium && marketplaceStatuses && Object.keys(marketplaceStatuses).length > 0) {
                statusHtml = renderPremiumStatusChips(marketplaceStatuses);
            } else {
                // Fallback to legacy single-status chip
                statusHtml = renderLegacyStatusChip(listingStatus);
            }
            
            statusColumn.html(statusHtml);
            
            // Update issues - show icon only if has issues, otherwise empty
            let issuesHtml = '';
            if (hasIssues) {
                issuesHtml = '<button type="button" class="momcs-issues-btn momcs-amz-issues-btn momcs-icon-tooltip" data-product-id="' + productId + '" title="View Issues">' +
                           '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-icon-issues"><path d="M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>' +
                           '</button>';
            } else {
                issuesHtml = '';
            }
            issuesColumn.html(issuesHtml);
            
            // Add a subtle highlight animation to show the row was updated
            productRow.addClass('momcs-updated-row');
            setTimeout(function() {
                productRow.removeClass('momcs-updated-row');
            }, 2000);
        }

        /**
         * Render Premium per-marketplace status chips.
         *
         * @param {Object} marketplaceStatuses Object keyed by marketplace ID with status data.
         * @returns {string} HTML string for the status chips container.
         */
        function renderPremiumStatusChips(marketplaceStatuses) {
            let html = '<div class="momcs-marketplace-chips">';
            
            $.each(marketplaceStatuses, function(mpId, mpData) {
                // Skip marketplaces without status data
                if (!mpData || !mpData.status) {
                    return true; // continue
                }
                
                const statusClass = getStatusClass(mpData.status);
                const mpInfo = (momcs_sync.marketplace_info && momcs_sync.marketplace_info[mpId]) || {};
                const flagClass = mpInfo.flag || mpId.toLowerCase().substring(0, 2);
                const marketplaceName = mpInfo.name || 'Amazon';
                const statusLabel = getStatusLabel(mpData.status);
                const statusTooltip = getStatusTooltip(mpData.status);
                const tooltipText = marketplaceName + ' - ' + statusLabel + ': ' + statusTooltip;
                
                // Render status icon based on status
                const statusIcon = renderStatusIcon(mpData.status);
                
                html += '<div class="momcs-marketplace-chip ' + statusClass + ' momcs-icon-tooltip" title="' + escapeHtml(tooltipText) + '">' +
                    statusIcon +
                    '<span class="momcs-mp-flag momcs-flag-' + flagClass + '"></span>' +
                    '</div>';
            });
            
            html += '</div>';
            return html;
        }
        
        /**
         * Render status icon based on status value.
         *
         * @param {string} status The status value.
         * @returns {string} HTML string for the status icon.
         */
        function renderStatusIcon(status) {
            const statusLower = status.toLowerCase();
            
            switch (statusLower) {
                case 'uploaded':
                case 'buyable':
                case 'success':
                    // Circle check icon for uploaded
                    return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-uploaded"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>';
                case 'discoverable':
                    // Binoculars icon for discoverable
                    return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-discoverable"><path d="M10 10h4"/><path d="M19 7V4a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3"/><path d="M20 21a2 2 0 0 0 2-2v-3.851c0-1.39-2-2.962-2-4.829V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v11a2 2 0 0 0 2 2z"/><path d="M 22 16 L 2 16"/><path d="M4 21a2 2 0 0 1-2-2v-3.851c0-1.39 2-2.962 2-4.829V8a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2z"/><path d="M9 7V4a1 1 0 0 0-1-1H6a1 1 0 0 0-1 1v3"/></svg>';
                case 'processing':
                case 'pending':
                    // Loader icon for processing
                    return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-processing momcs-icon-spin"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/></svg>';
                case 'failed':
                case 'error':
                    // X circle icon for failed
                    return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-error"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>';
                default:
                    // Default icon
                    return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-default"><circle cx="12" cy="12" r="10"/></svg>';
            }
        }

        /**
         * Render legacy single-status chip (for Free users or fallback).
         *
         * @param {string} listingStatus The listing status value.
         * @returns {string} HTML string for the status chip.
         */
        function renderLegacyStatusChip(listingStatus) {
            var tooltip = escapeHtml(getStatusLabel(listingStatus) + ': ' + getStatusTooltip(listingStatus));
            switch (listingStatus) {
                case 'uploaded':
                case 'BUYABLE':
                    return '<div class="momcs-sync-status-chip success" title="' + tooltip + '"><span class="momcs-sync-status-dot"></span>' + escapeHtml(getStatusLabel(listingStatus)) + '</div>';
                case 'discoverable':
                case 'DISCOVERABLE':
                    return '<div class="momcs-sync-status-chip discoverable" title="' + tooltip + '"><span class="momcs-sync-status-dot"></span>Discoverable</div>';
                case 'processing':
                    return '<div class="momcs-sync-status-chip processing" title="' + tooltip + '">' +
                           '<svg width="12" height="12" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 4px; flex-shrink: 0;"><path d="M7.706 0.290 C 7.484 0.362,7.356 0.490,7.294 0.699 C 7.259 0.816,7.253 1.088,7.253 2.508 C 7.253 4.389,7.251 4.365,7.443 4.557 C 7.700 4.813,8.300 4.813,8.557 4.557 C 8.749 4.365,8.747 4.389,8.747 2.508 C 8.747 0.688,8.744 0.656,8.596 0.480 C 8.472 0.333,8.339 0.284,8.040 0.276 C 7.893 0.272,7.743 0.278,7.706 0.290 M2.753 2.266 C 2.595 2.338,2.362 2.566,2.281 2.728 C 2.197 2.897,2.193 3.085,2.269 3.253 C 2.343 3.418,4.667 5.750,4.850 5.843 C 5.109 5.976,5.375 5.911,5.643 5.649 C 5.907 5.391,5.977 5.111,5.843 4.850 C 5.750 4.667,3.418 2.343,3.253 2.269 C 3.101 2.200,2.901 2.199,2.753 2.266 M12.853 2.282 C 12.730 2.339,12.520 2.536,11.518 3.541 C 10.597 4.464,10.316 4.762,10.271 4.860 C 10.195 5.025,10.196 5.216,10.272 5.378 C 10.342 5.528,10.572 5.764,10.727 5.845 C 10.884 5.927,11.117 5.926,11.280 5.843 C 11.447 5.757,13.757 3.447,13.843 3.280 C 13.926 3.118,13.927 2.884,13.846 2.729 C 13.764 2.572,13.552 2.364,13.392 2.283 C 13.213 2.192,13.048 2.192,12.853 2.282 M0.699 7.292 C 0.404 7.385,0.258 7.620,0.258 7.999 C 0.259 8.386,0.403 8.618,0.698 8.706 C 0.816 8.741,1.079 8.747,2.508 8.747 C 3.997 8.747,4.196 8.742,4.318 8.702 C 4.498 8.644,4.644 8.498,4.702 8.318 C 4.788 8.053,4.745 7.677,4.608 7.491 C 4.578 7.451,4.492 7.384,4.417 7.343 L 4.280 7.267 2.547 7.261 C 1.152 7.257,0.791 7.263,0.699 7.292 M11.745 7.278 C 11.622 7.308,11.452 7.411,11.392 7.492 C 11.255 7.677,11.212 8.053,11.298 8.318 C 11.356 8.498,11.502 8.644,11.682 8.702 C 11.804 8.742,12.003 8.747,13.492 8.747 C 14.921 8.747,15.184 8.741,15.302 8.706 C 15.597 8.618,15.741 8.386,15.742 7.999 C 15.742 7.614,15.595 7.383,15.290 7.291 C 15.187 7.260,14.864 7.254,13.496 7.256 C 12.578 7.258,11.790 7.268,11.745 7.278 M4.853 10.282 C 4.730 10.339,4.520 10.536,3.518 11.541 C 2.597 12.464,2.316 12.762,2.271 12.860 C 2.195 13.025,2.196 13.216,2.272 13.378 C 2.342 13.528,2.572 13.764,2.727 13.845 C 2.884 13.927,3.117 13.926,3.280 13.843 C 3.447 13.757,5.757 11.447,5.843 11.280 C 5.926 11.118,5.927 10.884,5.846 10.729 C 5.764 10.572,5.552 10.364,5.392 10.283 C 5.213 10.192,5.048 10.192,4.853 10.282 M10.753 10.266 C 10.595 10.338,10.362 10.566,10.281 10.728 C 10.197 10.897,10.193 11.085,10.269 11.253 C 10.343 11.418,12.667 13.750,12.850 13.843 C 13.109 13.976,13.375 13.911,13.643 13.649 C 13.907 13.391,13.977 13.111,13.843 12.850 C 13.750 12.667,11.418 10.343,11.253 10.269 C 11.101 10.200,10.901 10.199,10.753 10.266 M7.745 11.277 C 7.620 11.309,7.451 11.412,7.392 11.492 C 7.254 11.678,7.253 11.691,7.253 13.489 C 7.253 14.921,7.259 15.184,7.294 15.302 C 7.382 15.597,7.615 15.741,8.000 15.741 C 8.385 15.741,8.618 15.597,8.706 15.302 C 8.768 15.090,8.767 11.875,8.704 11.690 C 8.644 11.514,8.575 11.430,8.420 11.346 C 8.310 11.286,8.246 11.271,8.057 11.264 C 7.930 11.259,7.790 11.265,7.745 11.277 " stroke="none" fill-rule="evenodd" fill="#996800"/></svg>' +
                           'Processing</div>';
                case 'pending':
                    return '<div class="momcs-sync-status-chip pending" title="' + tooltip + '"><span class="momcs-sync-status-dot"></span>Pending</div>';
                case 'failed':
                    return '<div class="momcs-sync-status-chip error" title="' + tooltip + '"><span class="momcs-sync-status-dot"></span>Failed</div>';
                default:
                    return '<div class="momcs-sync-status-chip danger" title="' + tooltip + '"><span class="momcs-sync-status-dot"></span>Not uploaded</div>';
            }
        }

        /**
         * Get CSS class for a status value.
         *
         * @param {string} status The status value.
         * @returns {string} The CSS class name.
         */
        function getStatusClass(status) {
            const statusMap = {
                'uploaded': 'success',
                'BUYABLE': 'success',
                'discoverable': 'discoverable',
                'DISCOVERABLE': 'discoverable',
                'processing': 'processing',
                'pending': 'pending',
                'failed': 'error'
            };
            return statusMap[status] || 'danger';
        }

        /**
         * Get human-readable label for a status value.
         *
         * @param {string} status The status value.
         * @returns {string} The human-readable status label.
         */
        function getStatusLabel(status) {
            const labelMap = {
                'uploaded': 'Uploaded',
                'BUYABLE': 'Buyable',
                'discoverable': 'Discoverable',
                'DISCOVERABLE': 'Discoverable',
                'processing': 'Processing',
                'pending': 'Pending',
                'failed': 'Failed'
            };
            return labelMap[status] || 'Not uploaded';
        }

        /**
         * Get descriptive tooltip text for a status value.
         *
         * @param {string} status The status value.
         * @returns {string} Descriptive tooltip text.
         */
        function getStatusTooltip(status) {
            const tooltipMap = {
                'uploaded': "Your product details have been sent to Amazon, but they're still being processed. Wait a bit or check for errors to move forward.",
                'BUYABLE': 'Great news! Customers can find your product AND buy it right now. It has price, stock, and follows all Amazon rules.',
                'discoverable': "Customers can see and search for your product on Amazon. But they can't buy it yet \u2014 fix issues like price or stock to make it buyable.",
                'DISCOVERABLE': "Customers can see and search for your product on Amazon. But they can't buy it yet \u2014 fix issues like price or stock to make it buyable.",
                'processing': 'Your product is currently being processed by Amazon. This may take a few minutes.',
                'pending': 'Your product listing is pending. Amazon is reviewing the submission.',
                'failed': 'The listing failed. Check the Issues column for details on what went wrong.'
            };
            return tooltipMap[status] || 'This product has not been uploaded to Amazon yet.';
        }

        /**
         * Escape HTML special characters to prevent XSS.
         *
         * @param {string} text The text to escape.
         * @returns {string} The escaped text.
         */
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function finishRefresh(button, statusColumns, issuesColumns) {
            // Remove loading state from button
            button.removeClass('is-loading').prop('disabled', false);
            
            // Remove any remaining shimmer effects from body cells only
            statusColumns.removeClass('momcs-shimmer-active');
            issuesColumns.removeClass('momcs-shimmer-active');
        }

    });
    
    /**
     * Get current date and time in localized format
     *
     * @return {string} Formatted date and time
     */
    function getCurrentDateTime() {
        const now = new Date();
        return now.toLocaleString();
    }
})(jQuery); 