/**
 * Amazon Product Sync JavaScript for miniOrange WooCommerce Amazon Sync Plugin
 * Premium plan feature for comprehensive product synchronization from Amazon
 *
 * Handles the UI interactions for syncing complete product details from Amazon's
 * SearchListings API to WooCommerce, including progress tracking and sync controls.
 *
 * @package    MOMCS_Sync
 * @since      1.0.0
 */

const amazonProductSyncManager = {
    // Current sync session
    currentSyncSession: null,
    progressTimer: null,
    
    /**
     * Initialize Amazon product sync manager
     * 
     * @since 1.0.0
     */
    init: function() {
        this.bindEvents();
        this.checkExistingSync();
    },
    
    /**
     * Bind UI events
     * 
     * @since 1.0.0
     */
    bindEvents: function() {
        jQuery('#momcs-sync-from-amazon-btn').on('click', this.startSync.bind(this));
        jQuery(document).on('click', '.momcs-product-pause-btn', this.pauseSync.bind(this));
        jQuery(document).on('click', '.momcs-product-resume-btn', this.resumeSync.bind(this));
        jQuery(document).on('click', '.momcs-product-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 momcsProductSync !== 'undefined' && momcsProductSync.existingSyncSession) {
            this.currentSyncSession = momcsProductSync.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 momcsProductSync === 'undefined' || !momcsProductSync.isPremium) {
            alert('Amazon product sync is available only in premium plan. Please upgrade to access this feature.');
            return;
        }
        
        // Show channel selection popup using existing function from admin.js
        if (typeof showChannelSelectionPopup === 'function') {
            showChannelSelectionPopup([], 'amazon-product-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) {
            this.showError(momcsProductSync.strings.noChannelsSelected || 'No channels selected for product sync.');
            return;
        }
        
        // Disable sync button
        jQuery('#momcs-sync-from-amazon-btn').prop('disabled', true);
        
        jQuery.ajax({
            url: momcsProductSync.ajaxUrl,
            type: 'POST',
            data: {
                action: 'momcs_start_amazon_product_sync',
                security: momcsProductSync.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 || 'Failed to start product sync');
                    jQuery('#momcs-sync-from-amazon-btn').prop('disabled', false);
                }
            },
            error: (xhr, status, error) => {
                this.showError('Failed to start product sync: ' + error);
                jQuery('#momcs-sync-from-amazon-btn').prop('disabled', false);
            }
        });
    },
    
    /**
     * Show progress UI container with loading skeleton
     *
     * @since 1.0.0
     */
    showProgressUI: function() {
        const $progressContainer = jQuery('#momcs-product-sync-progress');
        if ($progressContainer.length) {
            $progressContainer.show();
            $progressContainer.html(`
                <div class="momcs-psp-card">
                    <div class="momcs-psp-header">
                        <span class="momcs-psp-header-icon">
                            <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"><path d="m17 18-1.535 1.605a5 5 0 0 1-8-1.5"/><path d="M17 22v-4h-4"/><path d="M20.996 15.251A4.5 4.5 0 0 0 17.495 8h-1.79a7 7 0 1 0-12.709 5.607"/><path d="M7 10v4h4"/><path d="m7 14 1.535-1.605a5 5 0 0 1 8 1.5"/></svg>
                        </span>
                        <h3 class="momcs-psp-title">${momcsProductSync.strings.syncInProgress || 'Amazon Product Sync'}</h3>
                        <span class="momcs-psp-live-badge">
                            <span class="momcs-psp-live-dot"></span>Live
                        </span>
                    </div>
                    <div class="momcs-psp-body">
                        <div class="momcs-psp-loading">
                            <span class="momcs-psp-spinner"></span>
                            <span>${momcsProductSync.strings.initializing || 'Initializing product sync\u2026'}</span>
                        </div>
                    </div>
                </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-product-sync-progress');
        if (!$progressContainer.length) {
            return;
        }

        const isLive = progressData.status === 'processing';

        let channelHtml = '';
        if (progressData.channels && progressData.channels.length > 0) {
            progressData.channels.forEach((channel, index) => {
                const pct       = Math.min(100, Math.max(0, parseInt(channel.progress) || 0));
                const statusBadge = this.getStatusBadge(channel.status);
                const statusIcon  = this.getStatusSvg(channel.status);

                channelHtml += `
                    <div class="momcs-psp-channel" data-status="${this.escapeHtml(channel.status)}">
                        <div class="momcs-psp-channel-row">
                            <span class="momcs-psp-channel-icon">${statusIcon}</span>
                            <span class="momcs-psp-channel-name">${this.escapeHtml(channel.name || 'Channel ' + (index + 1))}</span>
                            ${statusBadge}
                            <span class="momcs-psp-pct">${pct}%</span>
                        </div>
                        <div class="momcs-psp-bar-track">
                            <div class="momcs-psp-bar-fill" style="width:${pct}%"></div>
                        </div>
                        <div class="momcs-psp-channel-meta">
                            <span class="momcs-psp-meta-chip">
                                <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>
                                Batch ${channel.current_batch || 0}&thinsp;/&thinsp;${channel.total_batches || '?'}
                            </span>
                            ${channel.total_items ? `<span class="momcs-psp-meta-chip"><svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>${channel.total_items} items</span>` : ''}
                        </div>
                    </div>`;
            });
        }

        const overallBadge  = progressData.status ? this.getStatusBadge(progressData.status, true) : '';
        const startedRow    = progressData.started_at
            ? `<div class="momcs-psp-footer-meta"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> Started: ${this.escapeHtml(progressData.started_at)}</div>`
            : '';

        const html = `
            <div class="momcs-psp-card">
                <div class="momcs-psp-header">
                    <span class="momcs-psp-header-icon">
                        <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"><path d="m17 18-1.535 1.605a5 5 0 0 1-8-1.5"/><path d="M17 22v-4h-4"/><path d="M20.996 15.251A4.5 4.5 0 0 0 17.495 8h-1.79a7 7 0 1 0-12.709 5.607"/><path d="M7 10v4h4"/><path d="m7 14 1.535-1.605a5 5 0 0 1 8 1.5"/></svg>
                    </span>
                    <h3 class="momcs-psp-title">${momcsProductSync.strings.syncInProgress || 'Amazon Product Sync'}</h3>
                    ${isLive ? '<span class="momcs-psp-live-badge"><span class="momcs-psp-live-dot"></span>Live</span>' : overallBadge}
                </div>
                <div class="momcs-psp-body">
                    ${channelHtml || '<div class="momcs-psp-loading"><span class="momcs-psp-spinner"></span><span>Loading progress\u2026</span></div>'}
                </div>
                <div class="momcs-psp-controls-row">
                    ${this.generateControlButtons(progressData.status)}
                    ${startedRow}
                </div>
            </div>`;

        $progressContainer.html(html);

        // Disable/enable the main sync button based on status
        if (progressData.status === 'processing' || progressData.status === 'paused') {
            jQuery('#momcs-sync-from-amazon-btn').prop('disabled', true);
        } else {
            jQuery('#momcs-sync-from-amazon-btn').prop('disabled', false);
        }
    },
    
    /**
     * Get SVG icon for a channel status (replaces old emoji method)
     *
     * @since 1.0.0
     * @param {string} status Channel status
     * @returns {string} SVG icon HTML string
     */
    getStatusSvg: function(status) {
        const attrs = 'xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';
        switch (status) {
            case 'completed':
                return `<svg ${attrs} class="momcs-psp-status-icon status-completed"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`;
            case 'processing':
                return `<svg ${attrs} class="momcs-psp-status-icon status-processing momcs-psp-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 'paused':
                return `<svg ${attrs} class="momcs-psp-status-icon status-paused"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>`;
            case 'queued':
                return `<svg ${attrs} class="momcs-psp-status-icon status-queued"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`;
            case 'error':
            case 'failed':
                return `<svg ${attrs} class="momcs-psp-status-icon status-error"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`;
            default:
                return `<svg ${attrs} class="momcs-psp-status-icon status-default"><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>`;
        }
    },

    /**
     * Get a styled status badge pill for a given status
     *
     * @since 1.0.0
     * @param {string}  status   Status string
     * @param {boolean} large    Whether to use the larger "overall" badge variant
     * @returns {string} Badge HTML string
     */
    getStatusBadge: function(status, large) {
        const cls   = large ? 'momcs-psp-overall-badge' : 'momcs-psp-status-badge';
        const label = this.formatStatus(status);
        return `<span class="${cls} badge-${status}">${label}</span>`;
    },
    
    /**
     * Get CSS class for status
     * 
     * @since 1.0.0
     * @param {string} status Status string
     * @returns {string} CSS class
     */
    getStatusClass: function(status) {
        switch (status) {
            case 'completed':
                return 'status-completed';
            case 'processing':
                return 'status-processing';
            case 'paused':
                return 'status-paused';
            case 'queued':
                return 'status-queued';
            case 'error':
            case 'failed':
                return 'status-error';
            default:
                return 'status-default';
        }
    },
    
    /**
     * Generate progress bar HTML
     * 
     * @since 1.0.0
     * @param {number} progress Progress percentage
     * @returns {string} Progress bar HTML
     */
    generateProgressBar: function(progress) {
        const safeProgress = Math.min(100, Math.max(0, parseInt(progress) || 0));
        return `
            <div class="momcs-product-progress-bar">
                <div class="momcs-product-progress-fill" style="width: ${safeProgress}%"></div>
            </div>
        `;
    },
    
    /**
     * Format status for display
     * 
     * @since 1.0.0
     * @param {string} status Status string
     * @returns {string} Formatted status
     */
    formatStatus: function(status) {
        if (typeof momcsProductSync !== 'undefined' && momcsProductSync.strings) {
            switch (status) {
                case 'processing':
                    return momcsProductSync.strings.processing || 'Processing';
                case 'completed':
                    return momcsProductSync.strings.completed || 'Completed';
                case 'paused':
                    return momcsProductSync.strings.paused || 'Paused';
                case 'stopped':
                    return momcsProductSync.strings.stopped || 'Stopped';
                case 'error':
                    return momcsProductSync.strings.error || 'Error';
                case 'queued':
                    return momcsProductSync.strings.queued || 'Queued';
            }
        }
        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) {
        const pauseSvg  = '<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>';
        const resumeSvg = '<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>';
        const stopSvg   = '<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>';

        let btns = '';
        if (status === 'processing') {
            btns += `<button type="button" class="momcs-product-pause-btn">${pauseSvg}${momcsProductSync.strings.pauseSync || 'Pause'}</button>`;
            btns += `<button type="button" class="momcs-product-stop-btn">${stopSvg}${momcsProductSync.strings.stopSync || 'Stop'}</button>`;
        } else if (status === 'paused') {
            btns += `<button type="button" class="momcs-product-resume-btn">${resumeSvg}${momcsProductSync.strings.resumeSync || 'Resume'}</button>`;
            btns += `<button type="button" class="momcs-product-stop-btn">${stopSvg}${momcsProductSync.strings.stopSync || 'Stop'}</button>`;
        }

        return btns ? `<div class="momcs-psp-btn-group">${btns}</div>` : '';
    },
    
    /**
     * Pause sync
     * 
     * @since 1.0.0
     * @param {Event} e Click event
     */
    pauseSync: function(e) {
        const $button = jQuery(e.currentTarget);
        this.sendSyncCommand('pause', $button);
    },
    
    /**
     * Resume sync
     * 
     * @since 1.0.0
     * @param {Event} e Click event
     */
    resumeSync: function(e) {
        const $button = jQuery(e.currentTarget);
        this.sendSyncCommand('resume', $button);
    },
    
    /**
     * Stop sync
     * 
     * @since 1.0.0
     * @param {Event} e Click event
     */
    stopSync: function(e) {
        const confirmMessage = momcsProductSync.strings.confirmStop || 'Are you sure you want to stop the product sync? This will cancel all remaining operations.';
        if (confirm(confirmMessage)) {
            const $button = jQuery(e.currentTarget);
            this.sendSyncCommand('stop', $button);
        }
    },
    
    /**
     * Set button loading state
     * 
     * @since 1.0.0
     * @param {jQuery} $button Button element
     * @param {string} command Command being executed
     * @param {boolean} isLoading Whether to show loading state
     */
    setButtonLoading: function($button, command, isLoading) {
        if (!$button || !$button.length) {
            return;
        }
        
        const loadingTexts = {
            'pause': momcsProductSync.strings.pausing || 'Pausing...',
            'resume': momcsProductSync.strings.resuming || 'Resuming...',
            'stop': momcsProductSync.strings.stopping || 'Stopping...'
        };
        
        const normalTexts = {
            'pause': momcsProductSync.strings.pauseSync || 'Pause',
            'resume': momcsProductSync.strings.resumeSync || 'Resume',
            'stop': momcsProductSync.strings.stopSync || 'Stop'
        };
        
        if (isLoading) {
            $button.prop('disabled', true).text(loadingTexts[command] || 'Processing...');
            // Also disable sibling buttons to prevent conflicting actions
            $button.siblings('button').prop('disabled', true);
        } else {
            $button.prop('disabled', false).text(normalTexts[command] || command);
            $button.siblings('button').prop('disabled', false);
        }
    },
    
    /**
     * Send sync command (pause/resume/stop)
     * 
     * @since 1.0.0
     * @param {string} command Command to send
     * @param {jQuery} $button Button element that triggered the command
     */
    sendSyncCommand: function(command, $button) {
        if (!this.currentSyncSession) {
            return;
        }
        
        // Set button to loading state immediately
        this.setButtonLoading($button, command, true);
        
        jQuery.ajax({
            url: momcsProductSync.ajaxUrl,
            type: 'POST',
            data: {
                action: `momcs_${command}_amazon_product_sync`,
                security: momcsProductSync.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;
                        this.handleSyncComplete();
                    } else if (command === 'resume') {
                        this.startProgressPolling();
                    } else if (command === 'pause') {
                        this.stopProgressPolling();
                    }
                } else {
                    // Re-enable button on error
                    this.setButtonLoading($button, command, false);
                    this.showError(response.data.message || 'Failed to ' + command + ' sync');
                }
            },
            error: (xhr, status, error) => {
                // Re-enable button on error
                this.setButtonLoading($button, command, false);
                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: momcsProductSync.ajaxUrl,
            type: 'POST',
            data: {
                action: 'momcs_get_amazon_product_sync_progress',
                security: momcsProductSync.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(momcsProductSync.strings.syncCompleted || 'Product sync completed successfully!');
                            this.handleSyncComplete();
                        }
                        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 product sync progress, retrying...');
            }
        });
    },
    
    /**
     * Handle sync completion
     * 
     * @since 1.0.0
     */
    handleSyncComplete: function() {
        // Re-enable sync button
        jQuery('#momcs-sync-from-amazon-btn').prop('disabled', false);
        
        // Optionally refresh the page after a delay to show updated product data
        setTimeout(() => {
            const $progressContainer = jQuery('#momcs-product-sync-progress');
            $progressContainer.fadeOut(500, function() {
                // Page could be refreshed here if desired
                // location.reload();
            });
        }, 5000);
    },
    
    /**
     * Show styled error message
     *
     * @since 1.0.0
     * @param {string} message Error message
     */
    showError: function(message) {
        const $progressContainer = jQuery('#momcs-product-sync-progress');
        $progressContainer.show();
        $progressContainer.html(`
            <div class="momcs-psp-card">
                <div class="momcs-psp-alert momcs-psp-alert-error">
                    <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-psp-alert-icon"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                    <p>${this.escapeHtml(message)}</p>
                </div>
            </div>
        `);
        setTimeout(() => { $progressContainer.fadeOut(500); }, 10000);
    },

    /**
     * Show styled success message
     *
     * @since 1.0.0
     * @param {string} message Success message
     */
    showSuccess: function(message) {
        const $progressContainer = jQuery('#momcs-product-sync-progress');
        $progressContainer.show();
        const successHtml = `
            <div class="momcs-psp-alert momcs-psp-alert-success">
                <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-psp-alert-icon"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>
                <p>${this.escapeHtml(message)}</p>
            </div>`;
        if ($progressContainer.find('.momcs-psp-card').length) {
            $progressContainer.find('.momcs-psp-card').prepend(successHtml);
        } else {
            $progressContainer.html(`<div class="momcs-psp-card">${successHtml}</div>`);
        }
    },
    
    /**
     * Escape HTML to prevent XSS
     * 
     * @since 1.0.0
     * @param {string} text Text to escape
     * @returns {string} Escaped text
     */
    escapeHtml: function(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
};

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

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

