/**
 * Scheduled Sync JavaScript for miniOrange WooCommerce Amazon Sync Plugin
 * Premium plan feature for automatic scheduled product attribute synchronization
 *
 * @package    MOMCS_Sync
 * @since      1.0.0
 */

const scheduledSyncManager = {
    // Current channel configuration
    currentChannelUuid: null,
    currentScheduleSettings: null,
    
    // Form elements cache
    formElements: {},
    
    // Loading state management
    loadingStates: {
        form: false,
        preview: false,
        saving: false,
        deleting: false,
        attributes: false
    },
    
    // Validation state
    validationErrors: {},
    
    // Store pending selected attributes to apply after options are loaded
    pendingSelectedAttributes: null,
    
    /**
     * Initialize scheduled sync manager
     * 
     * @since 1.0.0
     */
    init: function() {
        this.cacheFormElements();
        this.bindEvents();
        this.loadInitialData();
    },
    
    /**
     * Cache form elements for performance.
     * Works in both legacy layout (#schedule_sync_settings) and two-card layout (#product-subtab-schedule).
     *
     * @since 1.0.0
     */
    cacheFormElements: function() {
        // Form may live in #schedule_sync_settings (legacy) or #product-subtab-schedule (two-card).
        var $formContainer = jQuery('#momcs-scheduled-sync-form-fields');
        this.formElements = {
            form: $formContainer,
            enabledCheckbox: jQuery('#momcs-schedule-enabled'),
            timeInput: jQuery('#momcs-schedule-time'),
            frequencyInput: jQuery('#momcs-schedule-frequency'),
            intervalSelect: jQuery('#momcs-schedule-interval'),
            attributesSelect: jQuery('#momcs-schedule-attributes'),
            previewContainer: jQuery('.momcs-schedule-preview'),
            submitButton: jQuery('#momcs-schedule-submit'),
            deleteButton: jQuery('#momcs-schedule-delete'),
            errorContainer: jQuery('.momcs-schedule-errors'),
            successContainer: jQuery('.momcs-schedule-success')
        };
    },
    
    /**
     * Bind UI events
     * 
     * @since 1.0.0
     */
    bindEvents: function() {
        const self = this;
        
        // Form submission - DISABLED: Now handled by Save and Next button integration
        // this.formElements.form.on('submit', this.handleFormSubmit.bind(this));
        
        // Prevent default form submission since we use Save and Next integration (no longer a form)
        // Note: No form element to bind submit to since it's now a div container
        
        // Schedule enabled/disabled toggle
        this.formElements.enabledCheckbox.on('change', this.handleScheduleToggle.bind(this));
        
        // Real-time preview updates
        this.formElements.timeInput.on('change blur', function() {
            self.updatePreview();
            self.updateScheduleCardSummary();
        });
        this.formElements.frequencyInput.on('input change', function() {
            self.updatePreview();
            self.updateScheduleCardSummary();
        });
        this.formElements.intervalSelect.on('change', function() {
            self.updatePreview();
            self.updateScheduleCardSummary();
        });
        
        // Form validation
        this.formElements.timeInput.on('blur', this.validateTimeInput.bind(this));
        this.formElements.frequencyInput.on('blur', this.validateFrequencyInput.bind(this));
        this.formElements.attributesSelect.on('change', this.validateAttributeSelection.bind(this));
        
        // Delete schedule - HIDDEN since using integrated workflow
        this.formElements.deleteButton.hide();
        
        // Attribute selection management
        this.initializeAttributeSelect();
    },
    
    /**
     * Load initial data on page load
     * 
     * @since 1.0.0
     */
    loadInitialData: function() {
        // Check if we have channel UUID from global configuration
        if (typeof momcsScheduledSync !== 'undefined' && momcsScheduledSync.channel_uuid) {
            this.currentChannelUuid = momcsScheduledSync.channel_uuid;
            this.loadScheduleSettings();
            this.loadAvailableAttributes();
        }
    },
    
    /**
     * Load existing schedule settings for channel
     * 
     * @since 1.0.0
     */
    loadScheduleSettings: function() {
        if (!this.currentChannelUuid) {
            console.warn('No channel UUID available for loading schedule settings');
            return;
        }
        
        console.log('🔄 Loading schedule settings for channel:', this.currentChannelUuid);
        console.log('- AJAX URL:', momcsScheduledSync.ajaxUrl);
        console.log('- Action:', momcsScheduledSync.actions.getSettings);
        console.log('- Nonce:', momcsScheduledSync.nonce);
        
        this.setLoadingState('form', true);
        this.clearMessages();
        
        jQuery.ajax({
            url: momcsScheduledSync.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: momcsScheduledSync.actions.getSettings,
                channel_uuid: this.currentChannelUuid,
                security: momcsScheduledSync.nonce
            },
            success: this.handleLoadSettingsSuccess.bind(this),
            error: this.handleLoadSettingsError.bind(this),
            complete: () => this.setLoadingState('form', false)
        });
    },
    
    /**
     * Handle successful schedule settings load
     * 
     * @since 1.0.0
     * @param {Object} response AJAX response
     */
    handleLoadSettingsSuccess: function(response) {
        console.log('✅ Schedule settings response received:', response);
        
        if (response.success && response.data && response.data.schedule_settings) {
            console.log('✅ Schedule settings found:', response.data.schedule_settings);
            this.currentScheduleSettings = response.data.schedule_settings;
            this.populateFormFields(response.data.schedule_settings);
            this.updatePreview();
        } else {
            console.log('ℹ️ No existing schedule found - initializing empty form');
            console.log('- response.success:', response.success);
            console.log('- response.data:', response.data);
            // No existing schedule - initialize empty form
            this.initializeEmptyForm();
        }
        
        // Hide shimmer loaders and show fields
        this.hideShimmers();
    },
    
    /**
     * Handle schedule settings load error
     * 
     * @since 1.0.0
     * @param {Object} xhr XMLHttpRequest object
     */
    handleLoadSettingsError: function(xhr) {
        console.error('❌ Failed to load schedule settings:', xhr);
        console.error('- Status:', xhr.status);
        console.error('- Response:', xhr.responseText);
        this.showError('Failed to load existing schedule settings. Please refresh the page and try again.');
        this.initializeEmptyForm();
        
        // Hide shimmer loaders and show fields even on error
        this.hideShimmers();
    },
    
    /**
     * Load available attributes for selection
     * 
     * @since 1.0.0
     */
    loadAvailableAttributes: function() {
        if (!this.currentChannelUuid) {
            return;
        }
        
        this.setLoadingState('attributes', true);
        
        jQuery.ajax({
            url: momcsScheduledSync.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: momcsScheduledSync.actions.getAvailableAttributes,
                channel_uuid: this.currentChannelUuid,
                security: momcsScheduledSync.nonce
            },
            success: this.handleLoadAttributesSuccess.bind(this),
            error: this.handleLoadAttributesError.bind(this),
            complete: () => this.setLoadingState('attributes', false)
        });
    },
    
    /**
     * Handle successful attributes load
     * 
     * @since 1.0.0
     * @param {Object} response AJAX response
     */
    handleLoadAttributesSuccess: function(response) {
        if (response.success && response.data && response.data.attributes) {
            this.populateAttributeOptions(response.data.attributes);
        } else {
            this.showError('Failed to load available attributes.');
        }
        
        // Hide shimmer for attributes field specifically
        jQuery('#momcs-schedule-attributes-field').removeClass('loading');
    },
    
    /**
     * Handle attributes load error
     * 
     * @since 1.0.0
     * @param {Object} xhr XMLHttpRequest object
     */
    handleLoadAttributesError: function(xhr) {
        console.error('Failed to load attributes:', xhr);
        this.showError('Failed to load available attributes. Please refresh the page.');
        
        // Hide shimmer for attributes field even on error
        jQuery('#momcs-schedule-attributes-field').removeClass('loading');
    },
    
    /**
     * Populate form fields with loaded settings
     * 
     * @since 1.0.0
     * @param {Object} settings Schedule settings object
     */
    populateFormFields: function(settings) {
        console.log('📝 Populating form fields with settings:', settings);
        console.log('- enabled:', settings.enabled);
        console.log('- scheduled_time:', settings.scheduled_time);
        console.log('- frequency:', settings.frequency);
        console.log('- interval:', settings.interval);
        console.log('- selected_attributes:', settings.selected_attributes);
        
        this.formElements.enabledCheckbox.prop('checked', settings.enabled === true);
        this.formElements.timeInput.val(settings.scheduled_time || '09:00');
        this.formElements.frequencyInput.val(settings.frequency || 1);
        this.formElements.intervalSelect.val(settings.interval || 'days');
        
        // Handle attribute selection with Tom Select
        if (settings.selected_attributes && Array.isArray(settings.selected_attributes) && this.tomSelectInstance) {
            // Check if Tom Select has options loaded
            const hasOptions = Object.keys(this.tomSelectInstance.options).length > 0;
            
            if (hasOptions) {
                console.log('✅ Setting selected attributes via Tom Select (options available):', settings.selected_attributes);
                this.tomSelectInstance.setValue(settings.selected_attributes, true);
                this.updateSelectionDisplay();
            } else {
                // Options not loaded yet - store for later
                console.log('⏳ Options not loaded yet, storing attributes for later:', settings.selected_attributes);
                this.pendingSelectedAttributes = settings.selected_attributes;
            }
        } else {
            console.log('⚠️ No selected attributes found or Tom Select not ready');
            if (settings.selected_attributes && Array.isArray(settings.selected_attributes)) {
                // Store for when Tom Select is ready
                this.pendingSelectedAttributes = settings.selected_attributes;
            }
        }
        
        this.handleScheduleToggle();
        this.updateScheduleCardSummary();
        
        console.log('✅ Form fields populated successfully');
    },
    
    /**
     * Update the product attribute schedule card summary (recurrence label only).
     *
     * @since 1.0.0
     */
    updateScheduleCardSummary: function() {
        const frequency = parseInt(this.formElements.frequencyInput.val(), 10) || 1;
        const interval = this.formElements.intervalSelect.val() || 'days';
        const recurrenceText = this.formatRecurrenceForCard(frequency, interval);
        jQuery('#momcs-schedule-card-product-attribute .momcs-schedule-card-recurrence-text').text(recurrenceText);
    },
    
    /**
     * Format frequency + interval as recurrence label for card.
     *
     * @since 1.0.0
     * @param {number} frequency Frequency number
     * @param {string} interval Interval (hours, days, months)
     * @return {string} Label e.g. "Daily", "Every 6 hours"
     */
    formatRecurrenceForCard: function(frequency, interval) {
        if (frequency === 1) {
            if (interval === 'days') return 'Daily';
            if (interval === 'hours') return 'Every hour';
            if (interval === 'months') return 'Monthly';
        }
        const intervalLabel = interval === 'hours' ? 'hours' : (interval === 'days' ? 'days' : 'months');
        return 'Every ' + frequency + ' ' + intervalLabel;
    },
    
    /**
     * Initialize empty form for new schedule
     * 
     * @since 1.0.0
     */
    initializeEmptyForm: function() {
        this.formElements.enabledCheckbox.prop('checked', false);
        this.formElements.timeInput.val('09:00');
        this.formElements.frequencyInput.val(1);
        this.formElements.intervalSelect.val('days');
        
        // Clear Tom Select
        if (this.tomSelectInstance) {
            this.tomSelectInstance.clear(true);
        }
        
        this.handleScheduleToggle();
        this.updatePreview();
        this.updateScheduleCardSummary();
    },
    
    /**
     * Populate attribute options dropdown
     * 
     * @since 1.0.0
     * @param {Array} attributes Available attributes array
     */
    populateAttributeOptions: function(attributes) {
        console.log('📋 Populating attributes:', attributes.length, 'attributes found');
        
        if (!this.tomSelectInstance) {
            console.warn('⚠️ Tom Select instance not ready, retrying...');
            setTimeout(() => this.populateAttributeOptions(attributes), 100);
            return;
        }
        
        // Clear existing options from Tom Select
        this.tomSelectInstance.clearOptions();
        
        // Add all attributes as simple options (no grouping to avoid layout issues)
        attributes.forEach(attr => {
            this.tomSelectInstance.addOption({
                value: attr.key,
                text: attr.label
            });
        });
        
        // Refresh Tom Select
        this.tomSelectInstance.refreshOptions(false);
        
        console.log('✅ Attributes populated into Tom Select');
        
        // Apply pending selected attributes if any
        if (this.pendingSelectedAttributes && Array.isArray(this.pendingSelectedAttributes)) {
            console.log('🔄 Applying pending selected attributes:', this.pendingSelectedAttributes);
            this.tomSelectInstance.setValue(this.pendingSelectedAttributes, true);
            this.updateSelectionDisplay();
            this.pendingSelectedAttributes = null; // Clear pending attributes
            console.log('✅ Pending attributes applied successfully');
        }
    },
    
    /**
     * Tom Select instance
     * 
     * @since 1.0.0
     */
    tomSelectInstance: null,
    
    /**
     * Initialize attribute select with Tom Select chip-based UI
     * 
     * @since 1.0.0
     */
    initializeAttributeSelect: function() {
        const select = this.formElements.attributesSelect;
        const self = this;
        
        console.log('🔧 Initializing Tom Select...');
        
        // Wait for Tom Select to be available
        if (typeof TomSelect === 'undefined') {
            console.warn('⏳ Tom Select not loaded yet, retrying...');
            setTimeout(() => this.initializeAttributeSelect(), 100);
            return;
        }
        
        // Check if already initialized
        if (this.tomSelectInstance) {
            console.log('ℹ️ Tom Select already initialized');
            return;
        }
        
        console.log('🚀 Creating Tom Select instance...');
        
        // Initialize Tom Select with chip-based UI configuration
        try {
            this.tomSelectInstance = new TomSelect(select[0], {
                plugins: ['remove_button', 'clear_button'],
                maxOptions: null,
                maxItems: null,
                placeholder: 'Search and select attributes...',
                searchField: ['text', 'value'],
                sortField: {
                    field: 'text',
                    direction: 'asc'
                },
                closeAfterSelect: false,
                hidePlaceholder: false,
                selectOnTab: true,
                create: false,
                persist: false,
                onInitialize: function() {
                    console.log('✅ Tom Select initialized successfully');
                },
                onChange: function(values) {
                    console.log('🔄 Tom Select values changed:', values);
                    self.updateSelectionDisplay();
                    self.updatePreview();
                    self.validateAttributeSelection();
                },
                onFocus: function() {
                    this.wrapper.classList.add('ts-focused');
                },
                onBlur: function() {
                    this.wrapper.classList.remove('ts-focused');
                }
            });
            
            console.log('✅ Tom Select instance created successfully!');
            
            // Add selection counter
            this.addSelectionCounter();
        } catch (error) {
            console.error('❌ Failed to initialize Tom Select:', error);
        }
    },
    
    /**
     * Add selection counter for Tom Select
     * 
     * @since 1.0.0
     */
    addSelectionCounter: function() {
        if (!this.tomSelectInstance) return;
        
        // Add counter element after Tom Select wrapper
        const wrapper = jQuery(this.tomSelectInstance.wrapper);
        
        // Initial update
        this.updateSelectionDisplay();
    },
    
    /**
     * Update selection counter display for Tom Select
     * 
     * @since 1.0.0
     */
    updateSelectionDisplay: function() {
        return;

    },
    
    /**
     * Handle schedule enabled/disabled toggle
     * 
     * @since 1.0.0
     */
    handleScheduleToggle: function() {
        const isEnabled = this.formElements.enabledCheckbox.is(':checked');
        
        // Enable/disable form fields
        this.formElements.timeInput.prop('disabled', !isEnabled);
        this.formElements.frequencyInput.prop('disabled', !isEnabled);
        this.formElements.intervalSelect.prop('disabled', !isEnabled);
        
        // Enable/disable Tom Select
        if (this.tomSelectInstance) {
            if (isEnabled) {
                this.tomSelectInstance.enable();
            } else {
                this.tomSelectInstance.disable();
            }
        }
        
        // Update form styling
        this.formElements.form.toggleClass('momcs-schedule-disabled', !isEnabled);
        
        // Update preview
        this.updatePreview();
        
        // Update delete button visibility
        this.updateDeleteButtonVisibility();
    },
    
    /**
     * Update schedule preview display
     * 
     * @since 1.0.0
     */
    updatePreview: function() {
        if (this.loadingStates.preview) {
            return;
        }
        
        this.setLoadingState('preview', true);
        
        const isEnabled = this.formElements.enabledCheckbox.is(':checked');
        const time = this.formElements.timeInput.val();
        const frequency = parseInt(this.formElements.frequencyInput.val()) || 1;
        const interval = this.formElements.intervalSelect.val();
        
        // Get selected attributes from Tom Select
        let selectedAttributes = [];
        if (this.tomSelectInstance) {
            const value = this.tomSelectInstance.getValue();
            selectedAttributes = Array.isArray(value) ? value : (value ? [value] : []);
        }
        
        if (!isEnabled) {
            this.displayPreview('Schedule is currently disabled');
            this.setLoadingState('preview', false);
            return;
        }
        
        if (!time || !interval || selectedAttributes.length === 0) {
            this.displayPreview('Please complete all required fields to see preview');
            this.setLoadingState('preview', false);
            return;
        }
        
        // Calculate preview text
        const previewText = this.generatePreviewText(time, frequency, interval, selectedAttributes);
        this.displayPreview(previewText);
        
        this.setLoadingState('preview', false);
    },
    
    /**
     * Generate human-readable preview text
     * 
     * @since 1.0.0
     * @param {string} time Scheduled time
     * @param {number} frequency Frequency number
     * @param {string} interval Interval type
     * @param {Array} attributes Selected attributes
     * @return {string} Preview text
     */
    generatePreviewText: function(time, frequency, interval, attributes) {
        // Format time
        const timeFormatted = this.formatTime(time);
        
        // Format frequency and interval
        let frequencyText;
        if (frequency === 1) {
            switch (interval) {
                case 'hours':
                    frequencyText = 'every hour';
                    break;
                case 'days':
                    frequencyText = 'daily';
                    break;
                case 'months':
                    frequencyText = 'monthly';
                    break;
                default:
                    frequencyText = `every ${interval}`;
            }
        } else {
            frequencyText = `every ${frequency} ${interval}`;
        }
        
        // Calculate next run time
        const nextRun = this.calculateNextRun(time, frequency, interval);
        
        // Format attributes
        const attributeCount = attributes.length;
        const attributeText = attributeCount === 1 ? '1 attribute' : `${attributeCount} attributes`;
        
        return `
            <strong>Schedule:</strong> Sync ${attributeText} ${frequencyText} at ${timeFormatted}<br>
            <strong>Next Run:</strong> ${nextRun}<br>
            <strong>Attributes:</strong> ${this.formatAttributeList(attributes)}
        `;
    },
    
    /**
     * Format time for display
     * 
     * @since 1.0.0
     * @param {string} time Time in HH:MM format
     * @return {string} Formatted time
     */
    formatTime: function(time) {
        try {
            const [hours, minutes] = time.split(':');
            const hour = parseInt(hours);
            const period = hour >= 12 ? 'PM' : 'AM';
            const displayHour = hour === 0 ? 12 : (hour > 12 ? hour - 12 : hour);
            return `${displayHour}:${minutes} ${period}`;
        } catch (e) {
            return time;
        }
    },
    
    /**
     * Calculate next run time
     * 
     * @since 1.0.0
     * @param {string} time Scheduled time
     * @param {number} frequency Frequency number
     * @param {string} interval Interval type
     * @return {string} Next run time
     */
    calculateNextRun: function(time, frequency, interval) {
        try {
            const now = new Date();
            const [hours, minutes] = time.split(':').map(n => parseInt(n));
            
            let nextRun = new Date();
            nextRun.setHours(hours, minutes, 0, 0);
            
            // If the time has passed today, start from tomorrow
            if (nextRun <= now) {
                nextRun.setDate(nextRun.getDate() + 1);
            }
            
            return nextRun.toLocaleString();
        } catch (e) {
            return 'Unable to calculate';
        }
    },
    
    /**
     * Format attribute list for preview
     * 
     * @since 1.0.0
     * @param {Array} attributes Selected attribute keys
     * @return {string} Formatted attribute list
     */
    formatAttributeList: function(attributes) {
        if (attributes.length === 0) {
            return 'None selected';
        }
        
        if (attributes.length <= 3) {
            return attributes.map(attr => this.getAttributeLabel(attr)).join(', ');
        }
        
        const first = attributes.slice(0, 3).map(attr => this.getAttributeLabel(attr)).join(', ');
        return `${first} and ${attributes.length - 3} more`;
    },
    
    /**
     * Get attribute label from key
     * 
     * @since 1.0.0
     * @param {string} key Attribute key
     * @return {string} Attribute label
     */
    getAttributeLabel: function(key) {
        if (this.tomSelectInstance && this.tomSelectInstance.options[key]) {
            return this.tomSelectInstance.options[key].text || key;
        }
        const option = this.formElements.attributesSelect.find(`option[value="${key}"]`);
        return option.length ? option.text() : key;
    },
    
    /**
     * Display preview text
     * 
     * @since 1.0.0
     * @param {string} text Preview text
     */
    displayPreview: function(text) {
        this.formElements.previewContainer.html(`
            <div class="momcs-schedule-preview-content">
                <h4>Schedule Preview</h4>
                <p>${text}</p>
            </div>
        `);
    },
    
    /**
     * Handle form submission
     * 
     * @since 1.0.0
     * @param {Event} e Form submit event
     */
    handleFormSubmit: function(e) {
        e.preventDefault();
        
        if (this.loadingStates.saving) {
            return;
        }
        
        // Validate form
        if (!this.validateForm()) {
            this.showError('Please correct the errors below and try again.');
            return;
        }
        
        const formData = this.collectFormData();
        const isUpdate = this.currentScheduleSettings !== null;
        
        this.setLoadingState('saving', true);
        this.clearMessages();
        
        const action = isUpdate ? momcsScheduledSync.actions.updateSchedule : momcsScheduledSync.actions.createSchedule;
        
        jQuery.ajax({
            url: momcsScheduledSync.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: action,
                channel_uuid: this.currentChannelUuid,
                scheduled_time: formData.scheduled_time,
                frequency: formData.frequency,
                interval: formData.interval,
                selected_attributes: formData.selected_attributes,
                security: momcsScheduledSync.nonce
            },
            success: this.handleSaveSuccess.bind(this, isUpdate),
            error: this.handleSaveError.bind(this),
            complete: () => this.setLoadingState('saving', false)
        });
    },
    
    /**
     * Collect form data for submission
     * 
     * @since 1.0.0
     * @return {Object} Form data object
     */
    collectFormData: function() {
        // Get selected attributes from Tom Select
        let selectedAttributes = [];
        if (this.tomSelectInstance) {
            const value = this.tomSelectInstance.getValue();
            selectedAttributes = Array.isArray(value) ? value : (value ? [value] : []);
        }
        
        return {
            enabled: this.formElements.enabledCheckbox.is(':checked'),
            scheduled_time: this.formElements.timeInput.val(),
            frequency: parseInt(this.formElements.frequencyInput.val()) || 1,
            interval: this.formElements.intervalSelect.val(),
            selected_attributes: selectedAttributes
        };
    },
    
    /**
     * Handle successful save operation
     * 
     * @since 1.0.0
     * @param {boolean} wasUpdate Whether this was an update operation
     * @param {Object} response AJAX response
     */
    handleSaveSuccess: function(wasUpdate, response) {
        if (response.success) {
            this.currentScheduleSettings = response.data;
            this.showSuccess(wasUpdate ? 'Schedule updated successfully!' : 'Schedule created successfully!');
            this.updateDeleteButtonVisibility();
        } else {
            this.showError(response.data?.message || 'Failed to save schedule. Please try again.');
        }
    },
    
    /**
     * Handle save operation error
     * 
     * @since 1.0.0
     * @param {Object} xhr XMLHttpRequest object
     */
    handleSaveError: function(xhr) {
        console.error('Failed to save schedule:', xhr);
        this.showError('Failed to save schedule. Please check your connection and try again.');
    },
    
    /**
     * Handle delete schedule
     * 
     * @since 1.0.0
     */
    handleDeleteSchedule: function() {
        if (!this.currentScheduleSettings) {
            this.showError('No schedule to delete.');
            return;
        }
        
        if (!confirm('Are you sure you want to delete this schedule? This action cannot be undone.')) {
            return;
        }
        
        this.setLoadingState('deleting', true);
        this.clearMessages();
        
        jQuery.ajax({
            url: momcsScheduledSync.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: momcsScheduledSync.actions.deleteSchedule,
                channel_uuid: this.currentChannelUuid,
                security: momcsScheduledSync.nonce
            },
            success: this.handleDeleteSuccess.bind(this),
            error: this.handleDeleteError.bind(this),
            complete: () => this.setLoadingState('deleting', false)
        });
    },
    
    /**
     * Handle successful delete operation
     * 
     * @since 1.0.0
     * @param {Object} response AJAX response
     */
    handleDeleteSuccess: function(response) {
        if (response.success) {
            this.currentScheduleSettings = null;
            this.initializeEmptyForm();
            this.showSuccess('Schedule deleted successfully!');
            this.updateDeleteButtonVisibility();
        } else {
            this.showError(response.data?.message || 'Failed to delete schedule.');
        }
    },
    
    /**
     * Handle delete operation error
     * 
     * @since 1.0.0
     * @param {Object} xhr XMLHttpRequest object
     */
    handleDeleteError: function(xhr) {
        console.error('Failed to delete schedule:', xhr);
        this.showError('Failed to delete schedule. Please try again.');
    },
    
    /**
     * Update delete button visibility
     * 
     * @since 1.0.0
     */
    updateDeleteButtonVisibility: function() {
        const hasSchedule = this.currentScheduleSettings !== null;
        this.formElements.deleteButton.toggle(hasSchedule);
    },
    
    /**
     * Validate entire form
     * 
     * @since 1.0.0
     * @return {boolean} Form validity
     */
    validateForm: function() {
        this.validationErrors = {};
        
        // Only validate if schedule is enabled
        if (!this.formElements.enabledCheckbox.is(':checked')) {
            return true;
        }
        
        this.validateTimeInput();
        this.validateFrequencyInput();
        this.validateAttributeSelection();
        
        // Display validation errors
        this.displayValidationErrors();
        
        return Object.keys(this.validationErrors).length === 0;
    },
    
    /**
     * Validate time input
     * 
     * @since 1.0.0
     */
    validateTimeInput: function() {
        const time = this.formElements.timeInput.val();
        const timePattern = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
        
        if (!time) {
            this.validationErrors.time = 'Scheduled time is required.';
        } else if (!timePattern.test(time)) {
            this.validationErrors.time = 'Please enter a valid time in HH:MM format.';
        }
    },
    
    /**
     * Validate frequency input
     * 
     * @since 1.0.0
     */
    validateFrequencyInput: function() {
        const frequency = parseInt(this.formElements.frequencyInput.val());
        
        if (!frequency || frequency < 1 || frequency > 99) {
            this.validationErrors.frequency = 'Frequency must be a number between 1 and 99.';
        }
    },
    
    /**
     * Validate attribute selection
     * 
     * @since 1.0.0
     */
    validateAttributeSelection: function() {
        // Get selected attributes from Tom Select
        let selectedAttributes = [];
        if (this.tomSelectInstance) {
            const value = this.tomSelectInstance.getValue();
            selectedAttributes = Array.isArray(value) ? value : (value ? [value] : []);
        }
        
        if (selectedAttributes.length === 0) {
            this.validationErrors.attributes = 'At least one attribute must be selected.';
        } else {
            // Remove error if previously set
            delete this.validationErrors.attributes;
        }
    },
    
    /**
     * Display validation errors
     * 
     * @since 1.0.0
     */
    displayValidationErrors: function() {
        // Clear previous error states
        this.formElements.form.find('.momcs-field-error').removeClass('momcs-field-error');
        this.formElements.form.find('.momcs-error-message').remove();
        
        // Add new error states
        Object.keys(this.validationErrors).forEach(field => {
            const message = this.validationErrors[field];
            let input;
            
            switch (field) {
                case 'time':
                    input = this.formElements.timeInput;
                    break;
                case 'frequency':
                    input = this.formElements.frequencyInput;
                    break;
                case 'attributes':
                    input = this.formElements.attributesSelect;
                    break;
            }
            
            if (input) {
                input.addClass('momcs-field-error');
                input.after(`<div class="momcs-error-message">${message}</div>`);
            }
        });
    },
    
    /**
     * Set loading state for specific operation
     * 
     * @since 1.0.0
     * @param {string} operation Operation name
     * @param {boolean} loading Loading state
     */
    setLoadingState: function(operation, loading) {
        this.loadingStates[operation] = loading;
        
        // Update button text (no longer showing overlay or disabling form)
        if (this.loadingStates.saving) {
            this.formElements.submitButton.text('Saving...');
        } else if (this.loadingStates.deleting) {
            this.formElements.deleteButton.text('Deleting...');
        } else {
            this.formElements.submitButton.text('Save Schedule');
            this.formElements.deleteButton.text('Delete Schedule');
        }
    },
    
    /**
     * Show success message
     * 
     * @since 1.0.0
     * @param {string} message Success message
     */
    showSuccess: function(message) {
        this.clearMessages();
        this.formElements.successContainer.html(`<div class="notice notice-success"><p>${message}</p></div>`).show();
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            this.formElements.successContainer.fadeOut();
        }, 5000);
    },
    
    /**
     * Show error message
     * 
     * @since 1.0.0
     * @param {string} message Error message
     */
    showError: function(message) {
        this.clearMessages();
        this.formElements.errorContainer.html(`<div class="notice notice-error"><p>${message}</p></div>`).show();
    },
    
    /**
     * Clear all messages
     * 
     * @since 1.0.0
     */
    clearMessages: function() {
        this.formElements.errorContainer.hide().empty();
        this.formElements.successContainer.hide().empty();
    },
    
    /**
     * Hide shimmer loaders and show actual fields
     * 
     * @since 1.0.0
     */
    hideShimmers: function() {
        // Remove loading class from all schedule fields
        jQuery('#momcs-schedule-enabled-field').removeClass('loading');
        jQuery('#momcs-schedule-time-field').removeClass('loading');
        jQuery('#momcs-schedule-frequency-field').removeClass('loading');
        // Attributes field is handled separately after attributes load
        
        console.log('✅ Shimmer loaders hidden, fields now visible');
    }
};

// Initialize when DOM is ready
jQuery(document).ready(function() {
    console.log('Scheduled Sync JS loaded');
    console.log('momcsScheduledSync available:', typeof momcsScheduledSync !== 'undefined');
    console.log('momcsScheduledSync data:', momcsScheduledSync);
    
        // Only initialize if we're on the scheduled sync page
    if (typeof momcsScheduledSync !== 'undefined') {
        console.log('Initializing scheduled sync manager...');
        
        // Legacy layout only: ensure schedule container is visible when Schedule Settings tab is clicked
        if (jQuery('#schedule_sync_settings').length) {
            jQuery(document).on('click', '.schedule_sync_tab a', function() {
                console.log('Schedule Settings tab clicked - ensuring form visibility');
                jQuery('.momcs-mapping-accordion, .momcs-field-mapping-container, .momcs-template-mapping-container').hide();
                jQuery('.momcs-scheduled-sync-container').show();
                jQuery('#momcs-scheduled-sync-form-fields').show();
                jQuery('#schedule_sync_settings').show().addClass('active');
                jQuery('.momcs-sync-settings-panel').not('#schedule_sync_settings').removeClass('active');
            });
            if (jQuery('#schedule_sync_settings').hasClass('active')) {
                jQuery('.momcs-scheduled-sync-container').show();
            }
        }
        // Two-card layout: schedule form lives in #product-subtab-schedule; visibility is controlled by .active class
        
        scheduledSyncManager.init();
    } else {
        console.error('momcsScheduledSync data not available - check PHP localization');
        
        // Hide shimmers if scheduled sync isn't available (fallback)
        jQuery('.momcs-schedule-field.loading').removeClass('loading');
    }
});

// Export for use in other scripts if needed
window.scheduledSyncManager = scheduledSyncManager;
