/**
 * Pro extension for field-option-data component
 * Adds bulk add options functionality
 */
;(function($) {
'use strict';

// Wait for Vue and field-option-data component to be available
// Try multiple times with increasing delays to catch the component
var attempts = 0;
var maxAttempts = 10;

function tryExtendComponent() {
    attempts++;
    
    if (typeof Vue !== 'undefined' && Vue.component('field-option-data')) {
        var component = Vue.component('field-option-data');
        var options = component.options;
            
            // Extend data function
            var originalData = options.data;
            
            options.data = function() {
                var data = originalData ? originalData.call(this) : {};
                
                if (!data.showBulkAddModal) {
                    data.showBulkAddModal = false;
                }
                
                return data;
            };
            
            // Extend mounted hook
            // IMPORTANT: In Vue 2, lifecycle hooks from mixins are merged into arrays
            // We must PUSH to the array, not replace it, or Vue won't call our hook
            var originalMounted = options.mounted;
            
            // Create our extension function
            var proExtensionMounted = function() {
                var self = this;
                
                // Wire up bulk add button click handler - try multiple times with delays
                var tryAttachHandler = function(attempt) {
                    attempt = attempt || 0;
                    
                    this.$nextTick(function () {
                        var bulkAddBtn = self.$el.querySelector('[data-wpuf-bulk-add-btn]');
                        
                        if (!bulkAddBtn) {
                            // Try searching in parent or document
                            bulkAddBtn = document.querySelector('[data-wpuf-bulk-add-btn]');
                        }
                        
                        if (bulkAddBtn) {
                            // Remove any existing handlers first
                            $(bulkAddBtn).off('click.bulkAdd');
                            $(bulkAddBtn).on('click.bulkAdd', function (e) {
                                e.preventDefault();
                                e.stopPropagation();
                                if (typeof self.open_bulk_add_modal === 'function') {
                                    self.open_bulk_add_modal();
                                }
                            });
                        } else if (attempt < 5) {
                            // Retry after a short delay
                            setTimeout(function() {
                                tryAttachHandler.call(self, attempt + 1);
                            }, 200);
                        }
                    });
                };
                
                tryAttachHandler.call(this, 0);
            };
            
            // Push our function to the array instead of replacing it
            // This ensures Vue processes all hooks correctly
            if (Array.isArray(originalMounted)) {
                originalMounted.push(proExtensionMounted);
                // options.mounted is already the array, no need to reassign
            } else if (typeof originalMounted === 'function') {
                options.mounted = [originalMounted, proExtensionMounted];
            } else {
                options.mounted = [proExtensionMounted];
            }
            
            // Extend methods
            if (!options.methods) {
                options.methods = {};
            }
            
            options.methods.open_bulk_add_modal = function () {
                this.showBulkAddModal = true;
            };
            
            options.methods.close_bulk_add_modal = function () {
                this.showBulkAddModal = false;
            };
            
            options.methods.bulkAddOptions = function (newOptionLabels) {
                var self = this;
                var maxOptions = 1000;
                var currentCount = this.options.length;
                var newCount = newOptionLabels.length;
                var totalCount = currentCount + newCount;
                
                // Validate total options count
                if (totalCount > maxOptions) {
                    var canAdd = maxOptions - currentCount;
                    this.warn({
                        title: 'Too Many Options',
                        text: 'You can only add ' + canAdd + ' more option(s). The limit is ' + maxOptions + ' options total.',
                        showCancelButton: false,
                        confirmButtonColor: "#46b450",
                    });
                    return;
                }
                
                // Validate that we have options to add
                if (newOptionLabels.length === 0) {
                    this.warn({
                        title: 'No Options',
                        text: 'Please enter at least one option.',
                        showCancelButton: false,
                        confirmButtonColor: "#46b450",
                    });
                    return;
                }
                
                // Add each option
                newOptionLabels.forEach(function (label) {
                    var value;
                    
                    // Generate value based on sync_value setting
                    if (self.sync_value) {
                        value = label.toLowerCase().replace(/\s/g, '_');
                    } else {
                        value = label;
                    }
                    
                    // Check if value already exists, if so make it unique
                    var existingValues = self.options.map(function (opt) {
                        return opt.value;
                    });
                    var originalValue = value;
                    var counter = 1;
                    while (existingValues.indexOf(value) !== -1) {
                        value = originalValue + '_' + counter;
                        counter++;
                    }
                    
                    self.options.push({
                        label: label,
                        value: value,
                        id: self.get_random_id()
                    });
                });
                
                // Close modal after adding
                this.close_bulk_add_modal();
            };
            
            options.methods.handleBulkAddError = function (errorMessage) {
                this.warn({
                    title: 'Error',
                    text: errorMessage,
                    showCancelButton: false,
                    confirmButtonColor: "#46b450",
                });
            };
            
            // Set up event delegation as a fallback
            $(document).off('click', '[data-wpuf-bulk-add-btn]').on('click', '[data-wpuf-bulk-add-btn]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                var $button = $(this);
                
                // Find the field-option-data component by looking for the table with class 'option-field-option-chooser'
                var $component = $button.closest('.panel-field-opt-text, .panel-field-opt');
                
                if (!$component.length) {
                    // Try finding by the table
                    $component = $button.parents().filter(function() {
                        return $(this).find('table.option-field-option-chooser').length > 0;
                    }).first();
                }
                
                var vueInstance = null;
                
                // Try multiple ways to find the Vue instance
                if ($component.length) {
                    // Method 1: Check the component element itself
                    vueInstance = $component[0].__vue__ || ($component.data && $component.data('__vue__'));
                    
                    // Method 2: Walk up the DOM tree looking for Vue instances
                    if (!vueInstance) {
                        var element = $component[0];
                        while (element && !vueInstance) {
                            if (element.__vue__) {
                                vueInstance = element.__vue__;
                                break;
                            }
                            element = element.parentElement;
                        }
                    }
                    
                    // Method 3: Search all child elements
                    if (!vueInstance) {
                        $component.find('*').each(function() {
                            if (this.__vue__ && this.__vue__.$options && this.__vue__.$options.name === 'field-option-data') {
                                vueInstance = this.__vue__;
                                return false; // break
                            }
                        });
                    }
                    
                    // Method 4: Search all Vue instances globally (last resort)
                    if (!vueInstance && typeof Vue !== 'undefined') {
                        var allElements = document.querySelectorAll('.panel-field-opt-text, .panel-field-opt');
                        for (var i = 0; i < allElements.length; i++) {
                            if (allElements[i].__vue__) {
                                var inst = allElements[i].__vue__;
                                // Check if this is a field-option-data instance
                                if (inst.$options && (inst.$options.name === 'field-option-data' || 
                                    (inst.$options._componentTag && inst.$options._componentTag === 'field-option-data') ||
                                    (inst.$el && $component.find(inst.$el).length > 0))) {
                                    vueInstance = inst;
                                    break;
                                }
                            }
                        }
                    }
                }
                
                if (vueInstance && typeof vueInstance.open_bulk_add_modal === 'function') {
                    vueInstance.open_bulk_add_modal();
                }
            });
            
            return true; // Success
        } else {
            if (attempts < maxAttempts) {
                // Try again with increasing delay
                var delay = 100 * attempts;
                setTimeout(tryExtendComponent, delay);
            }
            return false;
        }
}

// Start trying when document is ready
$(document).ready(function() {
    tryExtendComponent();
});

})(jQuery);

