/**
 * Centralized field initialization for WPUF Pro
 * Handles initialization of fields that require JavaScript plugins
 * Compatible with repeat fields and dynamic field instances
 */
(function($) {
    'use strict';

    var WPUF_Field_Initializer = {

        isInitializing: false,

        init: function() {
            this.initDateFields();
            this.initCountryFields();
            this.initPhoneFields();
            this.initRatingFields();
            this.initFileFields();
            this.bindEvents();
        },

        /**
         * Initialize date fields
         */
        initDateFields: function() {
            if (this.isInitializing) {
                return;
            }

            var dateFields = $('.wpuf-date-field:not(.wpuf-initialized)');
            
            // Clean up any existing date field initializations that might be orphaned
            $('.wpuf-date-field.hasDatepicker').each(function() {
                var $field = $(this);
                if (!$field.hasClass('wpuf-initialized')) {
                    try {
                        $field.datepicker('destroy');
                    } catch (error) {
                        $field.removeClass('hasDatepicker');
                    }
                }
            });

            if (dateFields.length === 0) {
                return;
            }

            this.isInitializing = true;

            dateFields.each(function(index) {
                var $field = $(this);

                // Remove any existing datepicker/datetimepicker initialization
                if ($field.hasClass('hasDatepicker')) {
                    try {
                        $field.datepicker('destroy');
                    } catch (error) {
                        $field.removeClass('hasDatepicker');
                    }
                }
                if ($field.hasClass('hasTimepicker')) {
                    try {
                        $field.datetimepicker('destroy');
                    } catch (error) {
                        $field.removeClass('hasTimepicker');
                    }
                }

                var format = $field.data('format') || 'dd/mm/yy';
                var timeEnabled = $field.data('time') === 'yes';
                var mintime = $field.data('mintime');
                var maxtime = $field.data('maxtime');

                var dateConfig = {
                    dateFormat: format,
                    changeMonth: true,
                    changeYear: true,
                    yearRange: '-100:+20'
                };

                // Add min/max date constraints if set
                if (mintime || maxtime) {
                    if (mintime) {
                        var mintimeParts = mintime.split('-');
                        dateConfig.minDate = new Date(mintimeParts[2], mintimeParts[1] - 1, mintimeParts[0]);
                    }
                    if (maxtime) {
                        var maxtimeParts = maxtime.split('-');
                        dateConfig.maxDate = new Date(maxtimeParts[2], maxtimeParts[1] - 1, maxtimeParts[0]);
                    }
                }

                // Initialize based on time setting
                try {
                    if (timeEnabled) {
                        $field.datetimepicker(dateConfig);
                    } else {
                        $field.datepicker(dateConfig);
                    }

                    // Mark as initialized
                    $field.addClass('wpuf-initialized');
                } catch (error) {
                    // Error initializing date field
                }
            });

            this.isInitializing = false;
        },

        /**
         * Initialize country fields
         */
        initCountryFields: function() {
            if (this.isInitializing) {
                return;
            }

            var countryFields = $('select[data-countries]:not(.wpuf-initialized)');

            if (countryFields.length === 0) {
                return;
            }

            // Check if selectize is available globally
            if (typeof $.fn.selectize === 'undefined') {
                return;
            }

            this.isInitializing = true;

            countryFields.each(function(index) {
                var $field = $(this);

                // Remove any existing selectize initialization
                if ($field.hasClass('selectized')) {
                    try {
                        $field[0].selectize.destroy();
                    } catch (error) {
                        $field.removeClass('selectized');
                    }
                }

                try {
                    // Safely parse JSON data with fallbacks
                    var countriesData = $field.data('countries');
                    var bannedCountriesData = $field.data('banned-countries');
                    var allowedCountriesData = $field.data('allowed-countries');

                    var countries = [];
                    var bannedCountries = [];
                    var allowedCountries = [];

                    // Parse countries data
                    if (countriesData) {
                        if (typeof countriesData === 'string') {
                            try {
                                countries = JSON.parse(countriesData);
                            } catch (e) {
                                countries = [];
                            }
                        } else if (Array.isArray(countriesData)) {
                            countries = countriesData;
                        } else {
                            countries = [];
                        }
                    }

                    // Parse banned countries data
                    if (bannedCountriesData) {
                        if (typeof bannedCountriesData === 'string') {
                            try {
                                bannedCountries = JSON.parse(bannedCountriesData);
                            } catch (e) {
                                bannedCountries = [];
                            }
                        } else if (Array.isArray(bannedCountriesData)) {
                            bannedCountries = bannedCountriesData;
                        }
                    }

                    // Parse allowed countries data
                    if (allowedCountriesData) {
                        if (typeof allowedCountriesData === 'string') {
                            try {
                                allowedCountries = JSON.parse(allowedCountriesData);
                            } catch (e) {
                                allowedCountries = [];
                            }
                        } else if (Array.isArray(allowedCountriesData)) {
                            allowedCountries = allowedCountriesData;
                        }
                    }

                    var listVisibilityOption = $field.data('list-visibility-option') || 'all';
                    var selectedCountry = $field.data('selected-country') || '';

                    // Build options based on visibility settings
                    var options = [];

                    // Ensure countries is an array
                    if (!Array.isArray(countries)) {
                        if (typeof countries === 'object' && countries !== null) {
                            // Convert object to array if needed
                            var countriesArray = [];
                            for (var code in countries) {
                                if (countries.hasOwnProperty(code)) {
                                    countriesArray.push({
                                        code: code,
                                        name: countries[code]
                                    });
                                }
                            }
                            countries = countriesArray;
                        } else {
                            countries = [];
                        }
                    }

                    if (listVisibilityOption === 'hide') {
                        // Show all countries except banned ones
                        countries.forEach(function(country) {
                            if (bannedCountries.indexOf(country.code) === -1) {
                                options.push({
                                    value: country.code,
                                    text: country.name
                                });
                            }
                        });
                    } else if (listVisibilityOption === 'show') {
                        // Show only allowed countries
                        allowedCountries.forEach(function(countryCode) {
                            var country = countries.find(function(c) { return c.code === countryCode; });
                            if (country) {
                                options.push({
                                    value: country.code,
                                    text: country.name
                                });
                            }
                        });
                    } else {
                        // Show all countries
                        countries.forEach(function(country) {
                            options.push({
                                value: country.code,
                                text: country.name
                            });
                        });
                    }

                    // Check if selectize is available
                    if (typeof $.fn.selectize !== 'undefined') {
                        // Initialize selectize
                        $field.selectize({
                            options: options,
                            items: selectedCountry ? [selectedCountry] : [],
                            placeholder: 'Select a country',
                            allowEmptyOption: true
                        });

                        // Mark as initialized
                        $field.addClass('wpuf-initialized');
                    } else {
                        // Fallback to regular select if selectize is not available
                        // Clear existing options
                        $field.empty();

                        // Add placeholder option
                        $field.append('<option value="">Select a country</option>');

                        // Add country options
                        options.forEach(function(option) {
                            var selected = option.value === selectedCountry ? 'selected' : '';
                            $field.append('<option value="' + option.value + '" ' + selected + '>' + option.text + '</option>');
                        });

                        // Mark as initialized
                        $field.addClass('wpuf-initialized');
                    }

                } catch (error) {
                    // Error initializing country field
                }
            });

            this.isInitializing = false;
        },

        /**
         * Initialize phone fields
         */
        initPhoneFields: function() {
            if (this.isInitializing) {
                return;
            }

            var phoneFields = $('input[type="tel"], input.wpuf_telephone:not(.wpuf-initialized)');
            
            // Clean up any existing phone field initializations that might be orphaned
            $('input.wpuf_telephone.iti').each(function() {
                var $field = $(this);
                if (!$field.hasClass('wpuf-initialized')) {
                    try {
                        $field.intlTelInput('destroy');
                    } catch (error) {
                        $field.removeClass('iti');
                    }
                }
            });

            if (phoneFields.length === 0) {
                return;
            }

            // Check if intlTelInput is available
            if (typeof window.intlTelInput === 'undefined') {
                return;
            }

            this.isInitializing = true;

            phoneFields.each(function(index) {
                var $field = $(this);

                // Remove any existing intlTelInput initialization
                if ($field.hasClass('iti')) {
                    try {
                        $field.intlTelInput('destroy');
                    } catch (error) {
                        $field.removeClass('iti');
                    }
                }

                try {
                    // Get field-specific settings
                    var showList = $field.data('show-list') || 'yes';
                    var defaultCountry = $field.data('default-country') || '';
                    var autoPlaceholder = $field.data('auto-placeholder') || 'yes';
                    var utilsScript = $field.data('utils-script') || '';

                    // Parse JSON data attributes
                    var onlyCountries = [];
                    var excludeCountries = [];

                    try {
                        var onlyCountriesData = $field.data('only-countries');
                        if (onlyCountriesData && typeof onlyCountriesData === 'string') {
                            onlyCountries = JSON.parse(onlyCountriesData);
                        } else if (Array.isArray(onlyCountriesData)) {
                            onlyCountries = onlyCountriesData;
                        }
                    } catch (e) {
                        // Error parsing only-countries data
                    }

                    try {
                        var excludeCountriesData = $field.data('exclude-countries');
                        if (excludeCountriesData && typeof excludeCountriesData === 'string') {
                            excludeCountries = JSON.parse(excludeCountriesData);
                        } else if (Array.isArray(excludeCountriesData)) {
                            excludeCountries = excludeCountriesData;
                        }
                    } catch (e) {
                        // Error parsing exclude-countries data
                    }

                    // Only initialize if show_list is 'yes'
                    if (showList === 'yes') {
                        // Check if intlTelInput is available
                        if (typeof window.intlTelInput !== 'undefined') {
                            var config = {};

                            if (utilsScript) {
                                config.utilsScript = utilsScript;
                            }

                            if (defaultCountry) {
                                config.initialCountry = defaultCountry;
                            }

                            if (onlyCountries && onlyCountries.length > 0) {
                                config.onlyCountries = onlyCountries;
                            }

                            if (excludeCountries && excludeCountries.length > 0) {
                                config.excludeCountries = excludeCountries;
                            }

                            if (autoPlaceholder === 'no') {
                                config.autoPlaceholder = 'off';
                            }

                            // Initialize international telephone input using the global function
                            try {
                                window.intlTelInput($field[0], config);
                            } catch (error) {
                                // Add a simple placeholder as fallback
                                if (!$field.attr('placeholder')) {
                                    $field.attr('placeholder', 'Enter phone number');
                                }
                            }
                        }
                    }

                    // Mark as initialized
                    $field.addClass('wpuf-initialized');
                } catch (error) {
                    // Error processing phone field
                }
            });

            this.isInitializing = false;
        },

        /**
         * Initialize rating fields
         */
        initRatingFields: function() {
            $('.wpuf-ratings:not(.wpuf-initialized)').each(function() {
                var $field = $(this);

                // Remove any existing barrating initialization
                if ($field.hasClass('br-theme-css-stars')) {
                    $field.barrating('destroy');
                }

                try {
                    $field.barrating({
                        theme: 'css-stars'
                    });

                    // Mark as initialized
                    $field.addClass('wpuf-initialized');
                } catch (error) {
                    // Error initializing rating field
                }
            });
        },

        /**
         * Initialize file upload fields
         */
        initFileFields: function() {
            $('.wpuf-file-upload:not(.wpuf-initialized)').each(function() {
                var $field = $(this);
                var uniqueId = $field.data('unique-id');
                var fieldName = $field.data('field-name');
                var count = $field.data('count') || 1;
                var allowedExt = $field.data('allowed-ext') || '';
                var maxSize = $field.data('max-size') || 1024;

                if (uniqueId && fieldName) {
                    try {
                        var uploader = new WPUF_Uploader(
                            'wpuf-' + uniqueId + '-pickfiles',
                            'wpuf-' + uniqueId + '-upload-container',
                            count,
                            fieldName,
                            allowedExt,
                            maxSize
                        );

                        if (typeof wpuf_plupload_items !== 'undefined') {
                            wpuf_plupload_items.push(uploader);
                        }

                        // Mark as initialized
                        $field.addClass('wpuf-initialized');
                                    } catch (error) {
                    // Error initializing file upload field
                }
                }
            });
        },

        /**
         * Clean up initialized fields (for cloned elements)
         */
        cleanupInitializedFields: function($container) {
            if (!$container) {
                $container = $('body');
            }

            // Remove initialization classes and destroy plugins
            var initializedFields = $container.find('.wpuf-initialized');

            initializedFields.each(function() {
                var $field = $(this);
                $field.removeClass('wpuf-initialized');

                // Destroy datepicker if exists - handle safely
                if ($field.hasClass('hasDatepicker')) {
                    try {
                        $field.datepicker('destroy');
                    } catch (error) {
                        // Remove the hasDatepicker class manually
                        $field.removeClass('hasDatepicker');
                        // Remove any datepicker-related elements
                        $field.siblings('.ui-datepicker').remove();
                    }
                }
                if ($field.hasClass('hasTimepicker')) {
                    try {
                        $field.datetimepicker('destroy');
                    } catch (error) {
                        // Remove the hasTimepicker class manually
                        $field.removeClass('hasTimepicker');
                        // Remove any datetimepicker-related elements
                        $field.siblings('.ui-datetimepicker').remove();
                    }
                }

                // Destroy barrating if exists
                if ($field.hasClass('br-theme-css-stars')) {
                    try {
                        $field.barrating('destroy');
                    } catch (error) {
                        // Remove barrating-related classes manually
                        $field.removeClass('br-theme-css-stars');
                        $field.siblings('.br-wrapper').remove();
                    }
                }

                // Destroy selectize if exists
                if ($field.hasClass('selectized') && $field[0].selectize) {
                    try {
                        $field[0].selectize.destroy();
                    } catch (error) {
                        // Remove selectize-related classes manually
                        $field.removeClass('selectized');
                        $field.siblings('.selectize-control').remove();
                    }
                }

                // Destroy intlTelInput if exists
                if ($field.hasClass('iti')) {
                    try {
                        $field.intlTelInput('destroy');
                    } catch (error) {
                        // Remove intlTelInput-related classes manually
                        $field.removeClass('iti');
                        $field.siblings('.iti').remove();
                    }
                }
            });
        },

        /**
         * Bind events for dynamic content
         */
        bindEvents: function() {
            // Re-initialize fields when new content is added (for repeat fields)
            $(document).on('wpuf-repeat-instance-added', function(event, $newInstance) {
                // Clean up any existing initializations in the new instance
                WPUF_Field_Initializer.cleanupInitializedFields($newInstance);

                // Re-initialize fields in the new instance with a longer delay
                setTimeout(function() {
                    WPUF_Field_Initializer.initDateFields();
                    WPUF_Field_Initializer.initCountryFields();
                    WPUF_Field_Initializer.initPhoneFields();
                    WPUF_Field_Initializer.initRatingFields();
                    WPUF_Field_Initializer.initFileFields();
                }, 200);
            });

            // Handle conditional logic updates
            $(document).on('wpuf-conditional-logic-updated', function() {
                WPUF_Field_Initializer.initDateFields();
                WPUF_Field_Initializer.initCountryFields();
                WPUF_Field_Initializer.initPhoneFields();
                WPUF_Field_Initializer.initRatingFields();
                WPUF_Field_Initializer.initFileFields();
            });
        },

        /**
         * Re-initialize all fields (useful for repeat field instances)
         */
        reinitialize: function() {
            this.initDateFields();
            this.initCountryFields();
            this.initPhoneFields();
            this.initRatingFields();
            this.initFileFields();
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        if (typeof WPUF_Field_Initializer !== 'undefined' && typeof WPUF_Field_Initializer.init === 'function') {
            WPUF_Field_Initializer.init();
        }
    });

    // Make available globally
    window.WPUF_Field_Initializer = WPUF_Field_Initializer;

})(jQuery);
