/**
 * ASIN Sync JavaScript for miniOrange WooCommerce Amazon Sync Plugin
 * Premium plan feature for bulk ASIN synchronization
 *
 * @package    MOMCS_Sync
 * @since      1.0.0
 */

const asinSyncManager = {
    // Current sync session
    currentSyncSession: null,
    progressTimer: null,
    
    /**
     * Initialize ASIN sync manager
     * 
     * @since 1.0.0
     */
    init: function() {
        this.bindEvents();
        this.checkExistingSync();
    },
    
    /**
     * Bind UI events
     * 
     * @since 1.0.0
     */
    bindEvents: function() {
        jQuery('#momcs-sync-asin-btn').on('click', this.startSync.bind(this));
        jQuery(document).on('click', '.momcs-asin-pause-btn', this.pauseSync.bind(this));
        jQuery(document).on('click', '.momcs-asin-resume-btn', this.resumeSync.bind(this));
        jQuery(document).on('click', '.momcs-asin-stop-btn', this.stopSync.bind(this));
    },
    
    /**
     * Check for existing sync session on page load
     * 
     * @since 1.0.0
     */
    checkExistingSync: function() {
        // Check if there's an ongoing sync session
        if (typeof momcsAsinSync !== 'undefined' && momcsAsinSync.existingSyncSession) {
            this.currentSyncSession = momcsAsinSync.existingSyncSession;
            this.showProgressUI();
            this.startProgressPolling();
            
            // Get initial progress data
            this.fetchProgress();
        }
    },
    
    /**
     * Start sync with channel selection
     * 
     * @since 1.0.0
     */
    startSync: function() {
        // Check if premium plan
        if (typeof momcsAsinSync === 'undefined' || !momcsAsinSync.isPremium) {
            alert('ASIN sync is available only in premium plan. Please upgrade to access this feature.');
            return;
        }
        
        // Show channel selection popup using extended function from admin.js
        if (typeof showChannelSelectionPopup === 'function') {
            showChannelSelectionPopup([], 'asin-sync');
        } else {
            alert('Channel selection not available. Please refresh the page and try again.');
        }
    },
    
    /**
     * Handle sync start after channel selection
     * 
     * @since 1.0.0
     * @param {Array} selectedChannels Array of selected channel UUIDs
     */
    handleSyncStart: function(selectedChannels) {
        if (!selectedChannels || selectedChannels.length === 0) {
            alert('No channels selected for ASIN sync.');
            return;
        }
        
        // Disable sync button
        jQuery('#momcs-sync-asin-btn').prop('disabled', true);
        
        jQuery.ajax({
            url: momcsAsinSync.ajaxUrl,
            type: 'POST',
            data: {
                action: 'momcs_start_asin_sync',
                security: momcsAsinSync.nonce,
                channel_ids: selectedChannels
            },
            success: (response) => {
                if (response.success) {
                    this.currentSyncSession = response.data.sync_session_id;
                    this.showProgressUI();
                    this.startProgressPolling();
                } else {
                    this.showError(response.data.message);
                    jQuery('#momcs-sync-asin-btn').prop('disabled', false);
                }
            },
            error: (xhr, status, error) => {
                this.showError('Failed to start ASIN sync: ' + error);
                jQuery('#momcs-sync-asin-btn').prop('disabled', false);
            }
        });
    },
    
    /**
     * Show progress UI container
     * 
     * @since 1.0.0
     */
    showProgressUI: function() {
        const $progressContainer = jQuery('#momcs-asin-sync-progress');
        if ($progressContainer.length) {
            $progressContainer.show();
            $progressContainer.html('<div class="momcs-asin-sync-status"><p>Initializing ASIN sync...</p></div>');
        }
    },
    
    /**
     * Update progress display with channel-specific information
     * 
     * @since 1.0.0
     * @param {Object} progressData Progress data from server
     */
    updateProgress: function(progressData) {
        const $progressContainer = jQuery('#momcs-asin-sync-progress');
        if (!$progressContainer.length) {
            return;
        }
        
        let html = '<div class="momcs-asin-sync-status">';
        html += '<h4>ASIN Sync Progress</h4>';
        
        if (progressData.channels && progressData.channels.length > 0) {
            progressData.channels.forEach((channel, index) => {
                const statusIcon = this.getStatusIcon(channel.status);
                const progressBar = this.generateProgressBar(channel.progress);
                
                html += `
                    <div class="momcs-channel-progress">
                        <div class="momcs-channel-info">
                            ${statusIcon} <strong>${channel.name}</strong>
                            <span class="momcs-progress-percentage">${channel.progress}%</span>
                        </div>
                        ${progressBar}
                    </div>
                `;
            });
        }
        
        // Add overall status message
        if (progressData.status) {
            html += `<p class="momcs-overall-status">Overall Status: ${this.formatStatus(progressData.status)}</p>`;
        }
        
        html += '</div>';
        
        // Add control buttons
        html += this.generateControlButtons(progressData.status);
        
        $progressContainer.html(html);
        
        // Hide sync button while sync is running
        if (progressData.status === 'processing' || progressData.status === 'paused') {
            jQuery('#momcs-sync-asin-btn').prop('disabled', true);
        } else {
            jQuery('#momcs-sync-asin-btn').prop('disabled', false);
        }
    },
    
    /**
     * Get status icon for channel status
     * 
     * @since 1.0.0
     * @param {string} status Channel status
     * @returns {string} Status icon HTML
     */
    getStatusIcon: function(status) {
        switch (status) {
            case 'completed':
                return '✅';
            case 'processing':
                return '🔄';
            case 'paused':
                return '⏸️';
            case 'queued':
                return '⏳';
            case 'error':
                return '❌';
            default:
                return '⚪';
        }
    },
    
    /**
     * Generate progress bar HTML
     * 
     * @since 1.0.0
     * @param {number} progress Progress percentage
     * @returns {string} Progress bar HTML
     */
    generateProgressBar: function(progress) {
        return `
            <div class="momcs-progress-bar">
                <div class="momcs-progress-fill" style="width: ${progress}%"></div>
            </div>
        `;
    },
    
    /**
     * Format status for display
     * 
     * @since 1.0.0
     * @param {string} status Status string
     * @returns {string} Formatted status
     */
    formatStatus: function(status) {
        return status.charAt(0).toUpperCase() + status.slice(1);
    },
    
    /**
     * Generate control buttons based on sync status
     * 
     * @since 1.0.0
     * @param {string} status Current sync status
     * @returns {string} Control buttons HTML
     */
    generateControlButtons: function(status) {
        let html = '<div class="momcs-asin-sync-controls">';
        
        if (status === 'processing') {
            html += '<button type="button" class="button momcs-asin-pause-btn">Pause Sync</button>';
            html += '<button type="button" class="button momcs-asin-stop-btn">Stop Sync</button>';
        } else if (status === 'paused') {
            html += '<button type="button" class="button button-primary momcs-asin-resume-btn">Resume Sync</button>';
            html += '<button type="button" class="button momcs-asin-stop-btn">Stop Sync</button>';
        }
        
        html += '</div>';
        return html;
    },
    
    /**
     * Pause sync
     * 
     * @since 1.0.0
     */
    pauseSync: function() {
        this.sendSyncCommand('pause');
    },
    
    /**
     * Resume sync
     * 
     * @since 1.0.0
     */
    resumeSync: function() {
        this.sendSyncCommand('resume');
    },
    
    /**
     * Stop sync
     * 
     * @since 1.0.0
     */
    stopSync: function() {
        if (confirm('Are you sure you want to stop the ASIN sync? This will cancel all remaining operations.')) {
            this.sendSyncCommand('stop');
        }
    },
    
    /**
     * Send sync command (pause/resume/stop)
     * 
     * @since 1.0.0
     * @param {string} command Command to send
     */
    sendSyncCommand: function(command) {
        if (!this.currentSyncSession) {
            return;
        }
        
        jQuery.ajax({
            url: momcsAsinSync.ajaxUrl,
            type: 'POST',
            data: {
                action: `momcs_${command}_asin_sync`,
                security: momcsAsinSync.nonce,
                sync_session_id: this.currentSyncSession
            },
            success: (response) => {
                if (response.success) {
                    // Extract progress data from response
                    if (response.data && response.data.progress) {
                        this.updateProgress(response.data.progress);
                    }
                    
                    // Show success message
                    if (response.data && response.data.message) {
                        this.showSuccess(response.data.message);
                    }
                    
                    // Handle command-specific actions
                    if (command === 'stop') {
                        this.stopProgressPolling();
                        this.currentSyncSession = null;
                    } else if (command === 'resume') {
                        this.startProgressPolling();
                    } else if (command === 'pause') {
                        this.stopProgressPolling();
                    }
                } else {
                    this.showError(response.data.message || 'Failed to ' + command + ' sync');
                }
            },
            error: (xhr, status, error) => {
                this.showError('Failed to ' + command + ' sync: ' + error);
            }
        });
    },
    
    /**
     * Start auto-polling for progress updates
     * 
     * @since 1.0.0
     */
    startProgressPolling: function() {
        if (this.progressTimer) {
            clearInterval(this.progressTimer);
        }
        
        this.progressTimer = setInterval(() => {
            this.fetchProgress();
        }, 3000); // Poll every 3 seconds
    },
    
    /**
     * Stop progress polling
     * 
     * @since 1.0.0
     */
    stopProgressPolling: function() {
        if (this.progressTimer) {
            clearInterval(this.progressTimer);
            this.progressTimer = null;
        }
    },
    
    /**
     * Fetch current progress from server
     * 
     * @since 1.0.0
     */
    fetchProgress: function() {
        if (!this.currentSyncSession) {
            this.stopProgressPolling();
            return;
        }
        
        jQuery.ajax({
            url: momcsAsinSync.ajaxUrl,
            type: 'POST',
            data: {
                action: 'momcs_get_asin_sync_progress',
                security: momcsAsinSync.nonce,
                sync_session_id: this.currentSyncSession
            },
            success: (response) => {
                if (response.success) {
                    this.updateProgress(response.data);
                    
                    // Stop polling if sync completed or stopped
                    if (response.data.status === 'completed' || response.data.status === 'stopped') {
                        this.stopProgressPolling();
                        if (response.data.status === 'completed') {
                            this.showSuccess('ASIN sync completed successfully!');
                        }
                        this.currentSyncSession = null;
                    }
                } else {
                    // If session not found, stop polling
                    this.stopProgressPolling();
                    this.currentSyncSession = null;
                }
            },
            error: () => {
                // Continue polling on network errors
                console.log('Failed to fetch ASIN sync progress, retrying...');
            }
        });
    },
    
    /**
     * Show error message
     * 
     * @since 1.0.0
     * @param {string} message Error message
     */
    showError: function(message) {
        const $progressContainer = jQuery('#momcs-asin-sync-progress');
        $progressContainer.show();
        $progressContainer.html(`
            <div class="momcs-asin-sync-error">
                <p><span class="dashicons dashicons-warning" style="color: #dc3232;"></span> ${message}</p>
            </div>
        `);
    },
    
    /**
     * Show success message
     * 
     * @since 1.0.0
     * @param {string} message Success message
     */
    showSuccess: function(message) {
        const $progressContainer = jQuery('#momcs-asin-sync-progress');
        $progressContainer.show();
        $progressContainer.html(`
            <div class="momcs-asin-sync-success">
                <p><span class="dashicons dashicons-yes-alt" style="color: #46b450;"></span> ${message}</p>
            </div>
        `);
        
        // Hide success message after 5 seconds
        setTimeout(() => {
            $progressContainer.fadeOut();
        }, 5000);
    }
};

// Make asinSyncManager available globally for admin.js integration
window.asinSyncManager = asinSyncManager;

// Initialize when DOM is ready
jQuery(document).ready(() => {
    if (typeof momcsAsinSync !== 'undefined' && momcsAsinSync.isPremium) {
        asinSyncManager.init();
    }
});