jQuery(document).ready(function($) {
    'use strict';
    
    // -------------------------------------------------------------------------
    // Sync sales button (Ventes tab)
    // -------------------------------------------------------------------------
    $('#flowdino-sync-sales').on('click', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#flowdino-sales-sync-result');
        var originalHtml = $button.html();

        $button.html('<span class="dashicons dashicons-update" style="vertical-align:middle;margin-right:4px;animation:spin 1s linear infinite;"></span> Synchronisation en cours…')
               .prop('disabled', true);
        $result.html('');

        $.ajax({
            url: flowdino_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'flowdino_sync_sales',
                nonce: flowdino_ajax.sync_sales_nonce
            },
            success: function(response) {
                if (response.success) {
                    var msg = '<div class="notice notice-success inline" style="padding:8px 12px;">' +
                              '<strong>✔ ' + response.data.message + '</strong>';

                    if (response.data.sites && Object.keys(response.data.sites).length > 0) {
                        msg += '<ul style="margin:6px 0 0 16px;">';
                        $.each(response.data.sites, function(name, site) {
                            msg += '<li>' + name + ' : ' + site.message + '</li>';
                        });
                        msg += '</ul>';
                    }

                    msg += '</div>';
                    $result.html(msg);

                    // Refresh the stats table (reload page after short delay)
                    setTimeout(function() { location.reload(); }, 2000);
                } else {
                    $result.html('<div class="notice notice-error inline" style="padding:8px 12px;">' +
                                 '<strong>✖ ' + response.data.message + '</strong></div>');
                }
            },
            error: function() {
                $result.html('<div class="notice notice-error inline" style="padding:8px 12px;">' +
                             '<strong>✖ Erreur lors de la synchronisation. Veuillez réessayer.</strong></div>');
            },
            complete: function() {
                $button.html(originalHtml).prop('disabled', false);
            }
        });
    });

    // Individual product sync
    $('.sync-product').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var productId = $button.data('product-id');
        var originalText = $button.text();
        
        $button.text('Syncing...').prop('disabled', true);
        
        $.ajax({
            url: flowdino_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'flowdino_sync_product',
                product_id: productId,
                nonce: flowdino_ajax.sync_nonce
            },
            success: function(response) {
                if (response.success) {
                    showNotice('Product synced successfully!', 'success');
                    // Update status in the table
                    var $row = $button.closest('tr');
                    $row.find('.flowdino-status').text('Synced').css('color', 'green');
                    var now = new Date();
                    $row.find('td:nth-child(3)').text(now.toLocaleString());
                } else {
                    showNotice('Sync failed: ' + response.message, 'error');
                }
            },
            error: function() {
                showNotice('Sync failed. Please try again.', 'error');
            },
            complete: function() {
                $button.text(originalText).prop('disabled', false);
            }
        });
    });
    
    // Bulk sync products with progress
    $('input[name="sync_all_products"], input[name="sync_pending_products"]').on('click', function(e) {
        var confirmed = confirm('This may take a while. Are you sure you want to continue?');
        if (!confirmed) {
            e.preventDefault();
        }
    });
    
    // Auto-refresh sync status every 30 seconds when on products tab
    if (window.location.href.indexOf('tab=products') > -1) {
        setInterval(function() {
            refreshSyncStatus();
        }, 30000);
    }
    
    // Category mapping auto-save
    $('select[name^="category_mapping"]').on('change', function() {
        var $select = $(this);
        var $row = $select.closest('tr');
        
        // Add visual feedback
        $row.css('background-color', '#fff3cd');
        setTimeout(function() {
            $row.css('background-color', '');
        }, 1000);
    });
    
    // Attribute mapping functions
    $('.add-attribute-mapping').on('click', function(e) {
        e.preventDefault();
        
        var $container = $(this).closest('.attribute-mapping');
        var $template = $container.find('.mapping-row:first').clone();
        
        // Clear values in cloned row
        $template.find('select').val('');
        
        // Add remove button if not present
        if ($template.find('.remove-mapping').length === 0) {
            $template.append('<button type="button" class="button remove-mapping">Remove</button>');
        }
        
        $container.find('.mapping-rows').append($template);
    });
    
    // Remove attribute mapping
    $(document).on('click', '.remove-mapping', function(e) {
        e.preventDefault();
        
        var $row = $(this).closest('.mapping-row');
        var $container = $row.closest('.attribute-mapping');
        
        // Don't remove if it's the only row
        if ($container.find('.mapping-row').length > 1) {
            $row.remove();
        }
    });
    
    // Validation for settings form
    $('form').on('submit', function(e) {
        var $form = $(this);
        
        // Email validation
        var email = $form.find('input[name="flowdino_email"]').val();
        if (email && !isValidEmail(email)) {
            e.preventDefault();
            showNotice('Please enter a valid email address.', 'error');
            return false;
        }
        
        // URL validation
        var apiUrl = $form.find('input[name="flowdino_api_url"]').val();
        if (apiUrl && !isValidUrl(apiUrl)) {
            e.preventDefault();
            showNotice('Please enter a valid API URL.', 'error');
            return false;
        }
    });
    
    // Helper functions
    function showNotice(message, type) {
        var noticeClass = 'notice-' + (type === 'error' ? 'error' : 'success');
        var $notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');
        
        $('.wrap h1').after($notice);
        
        // Auto-hide success notices after 5 seconds
        if (type === 'success') {
            setTimeout(function() {
                $notice.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
    }
    
    function refreshSyncStatus() {
        // This could be implemented to refresh the product sync status
        // without reloading the page
        console.log('Refreshing sync status...');
    }
    
    function isValidEmail(email) {
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
    
    function isValidUrl(url) {
        try {
            new URL(url);
            return true;
        } catch (_) {
            return false;
        }
    }
    
    // Initialize tooltips if available
    if (typeof $.fn.tooltip === 'function') {
        $('[title]').tooltip();
    }
    
    // Search functionality for products table
    $('#product-search').on('keyup', function() {
        var searchTerm = $(this).val().toLowerCase();
        var $rows = $('.wp-list-table tbody tr');
        
        $rows.each(function() {
            var $row = $(this);
            var productName = $row.find('td:first strong').text().toLowerCase();
            
            if (productName.indexOf(searchTerm) > -1) {
                $row.show();
            } else {
                $row.hide();
            }
        });
    });
    
    // Confirmation dialogs for destructive actions
    $('.delete-mapping, .reset-settings').on('click', function(e) {
        var action = $(this).text();
        var confirmed = confirm('Are you sure you want to ' + action.toLowerCase() + '? This action cannot be undone.');
        
        if (!confirmed) {
            e.preventDefault();
        }
    });
});
