import intlTelInput from "intl-tel-input";

//Formeo Custom code
Array.prototype.removeByValue = function (val) {
    const index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
    return this;
}

let attendee_prefilled_data = [];
let booking_attendee_prefilled_data = [];

export class EbFormeo {
  

    static getEditorJsonByCollectionType(editorJson, informationType) {
        let newJson = "";
        if (editorJson) {
            newJson = JSON.parse(JSON.stringify(editorJson));
            for (const [key, value] of Object.entries(newJson)) {
                if (key === 'fields') {
                    for (const [fieldId, fieldValues] of Object.entries(value)) {
                        if (fieldValues.attrs?.how_you_want_to_collect_information !== informationType) {
                            // delete newJson["fields"][fieldId];
                            for (const [key2, value2] of Object.entries(newJson)) {
                                if (key2 === 'columns') {
                                    for (const [columnId, columnValues] of Object.entries(value2)) {
                                        if (columnValues["children"].includes(fieldId)) {
                                            // column ID
                                            for (const [key3, value3] of Object.entries(newJson)) {
                                                if (key3 === 'rows') {
                                                    for (const [rowId, rowValues] of Object.entries(value3)) {
                                                        if (rowValues["children"].includes(columnId)) {
                                                            // row ID
                                                            for (const [key4, value4] of Object.entries(newJson)) {
                                                                if (key4 === 'stages') {
                                                                    for (const stageId of Object.keys(value4)) {
                                                                        const stageValues = value4[stageId];
                                                                        // console.log("stage=", stageId, stageValues, stageValues["children"])
                                                                        if (stageValues["children"].includes(rowId)) {
                                                                            stageValues["children"].removeByValue(rowId);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            delete newJson["rows"][rowId];
                                                        }
                                                    }
                                                }
                                            }
                                            delete newJson["columns"][columnId];
                                        }
                                    }
                                }
                            }
                            delete newJson["fields"][fieldId];
                        }
                    }
                }
            }
        }
        return newJson;
    };

    static filerEditorJsonByTicketType(editorJson, ticketSlug) {
        let newJson = "";
        if (editorJson) {
            newJson = JSON.parse(JSON.stringify(editorJson));
            for (const [key, value] of Object.entries(newJson)) {
                if (key === 'fields') {
                    for (const [fieldId, fieldValues] of Object.entries(value)) {
                        if (fieldValues.attrs?.show_this_question_for_specific_ticket_types) {
                            let isHideField = true;
                            if (Object.keys(fieldValues.attrs).includes(ticketSlug) && fieldValues.attrs[ticketSlug]) {
                                isHideField = false;
                            }
                            if (isHideField) {
                                for (const [key2, value2] of Object.entries(newJson)) {
                                    if (key2 === 'columns') {
                                        for (const [columnId, columnValues] of Object.entries(value2)) {
                                            if (columnValues["children"].includes(fieldId)) {
                                                // column ID
                                                for (const [key3, value3] of Object.entries(newJson)) {
                                                    if (key3 === 'rows') {
                                                        for (const [rowId, rowValues] of Object.entries(value3)) {
                                                            if (rowValues["children"].includes(columnId)) {
                                                                // row ID
                                                                for (const [key4, value4] of Object.entries(newJson)) {
                                                                    if (key4 === 'stages') {
                                                                        for (const stageId of Object.keys(value4)) {
                                                                            const stageValues = value4[stageId];
                                                                            if (stageValues["children"].includes(rowId)) {
                                                                                stageValues["children"].removeByValue(rowId);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                                delete newJson["rows"][rowId];
                                                            }
                                                        }
                                                    }
                                                }
                                                delete newJson["columns"][columnId];
                                            }
                                        }
                                    }
                                }
                                delete newJson["fields"][fieldId];
                            }
                        }
                    }
                }
            }
        }
        return newJson;
    }

    static renderAttendeeBuilderFields(editorJson, isUpdateAditionalInformation = false) {
        let attendeeEditorJson = this.getEditorJsonByCollectionType(editorJson, "from-each-attendees");
        let _this = this;
        $(".attendee_formeo_render").each(function (index) {
            let self = $(this);
            let formeo_ticket_slug = self.attr("formeo_ticket_slug");
            let attendeeEditorJsonByTicket = _this.filerEditorJsonByTicketType(attendeeEditorJson, formeo_ticket_slug);
            let renderer_selector = '#' + self.attr("id");
            let dynamic_renderer = new FormeoRenderer({
                renderContainer: renderer_selector,
            });
            if (attendeeEditorJsonByTicket) {
                dynamic_renderer.render(attendeeEditorJsonByTicket);
            }
            var attendee_index = self.attr("attendee_index");
            _this.appendAttendeeAnswersHiddenField($(renderer_selector));
            $(renderer_selector).find("textarea, select, input").each(function () {
                // console.log('this', this)
                var field_selector = $(this);
                let input_type = field_selector.attr('type');

                // for design purpose
                if (['number', 'file'].includes(input_type)) {
                    let wrap_class = '';
                    switch (input_type) {
                        case 'number':
                            wrap_class = 'attendee-number-field-wrap';
                            break;
                        case 'file':
                            wrap_class = 'attendee-file-field-wrap';
                            break;
                    }
                    field_selector.parent().addClass(wrap_class);
                }

                if (['checkbox', 'radio'].includes(input_type)) {
                    field_selector.parent().find('label').removeAttr('for');
                }

                if (field_selector.attr('type') === 'checkbox') {
                    field_selector.attr("name", field_selector.attr('name') + "[" + attendee_index + "][]");
                }
                else {
                    field_selector.attr("name", field_selector.attr('name') + "[" + attendee_index + "]");
                }
            });

            if (isUpdateAditionalInformation) {
                setTimeout(function () {
                    _this.prefillUpdateAditionalInformationAttendeeData(renderer_selector, attendee_index);
                }, 1000)
            } else {
                _this.prefillAttendeeData(renderer_selector);
            }
        });

        if (isUpdateAditionalInformation) {
            setTimeout(function () {
                _this.prefillUpdateAditionalInformationBookingData();
            }, 1000)
        }

        $('#attendeeInfo_form').on("input change select2:select", "input, select", function (e) {
            let self = $(this);
            if (self.val()) {
                self.removeClass('error');
                self.parent().find('label.error').remove();
            }
        });
    }

    static appendAttendeeAnswersHiddenField(attendee_wrapper) {
        let attendee_answer_inputs = attendee_wrapper.find("input[show-the-attendees-answer-on-their-order-confirmation-and-ticket=true], textarea[show-the-attendees-answer-on-their-order-confirmation-and-ticket=true], select[show-the-attendees-answer-on-their-order-confirmation-and-ticket=true]");
        for (let i = 0; i < attendee_answer_inputs.length; i++) {
            let attendee_answer_input = attendee_answer_inputs[i];
            let $attendee_answer_input = $(attendee_answer_input);
            let input_name = $attendee_answer_input.attr("name");
            input_name = input_name + "_answer_on_order_confirmation_and_ticket";
            let attendee_answer_hidden_input = '<input type="hidden" name="' + input_name + '">';
            $attendee_answer_input.closest(".f-field-group").find(".attendee_answer_hidden_input").remove();
            $(attendee_answer_input).closest(".f-field-group").append(attendee_answer_hidden_input)
        }

        //Answer on order confirmation  for Radio checkbox field
        let radio_checkbox_group_attributes = attendee_wrapper.find(".radio_checkbox_group_attribute[show-the-attendees-answer-on-their-order-confirmation-and-ticket=true]");
        for (let i = 0; i < radio_checkbox_group_attributes.length; i++) {
            let $element = $(radio_checkbox_group_attributes[i]);
            let $attendee_answer_input = $($element.find("input")[0]);
             let input_name = $attendee_answer_input.attr("name");
            input_name = input_name + "_answer_on_order_confirmation_and_ticket";
            let attendee_answer_hidden_input = '<input type="hidden" name="' + input_name + '">';
            $element.find(".attendee_answer_hidden_input").remove();
            $element.append(attendee_answer_hidden_input);
        }
    }

    static prefillUpdateAditionalInformationAttendeeData(renderer_selector, prefill_attendee_index) {
        if (attendee_prefilled_data[prefill_attendee_index]) {
            let attendee_index = renderer_selector.replace("#editor-form_", "")
            for (let [fieldName, fieldValue] of Object.entries(attendee_prefilled_data[prefill_attendee_index])) {
                fieldName = fieldName ? fieldName.trim() : fieldName;
                fieldValue = fieldValue ? fieldValue.trim() : fieldValue;
                this.prefillAdditionalContact(fieldName, fieldValue, attendee_index);
                prefillAttendeeBuilderFields(fieldName, fieldValue, renderer_selector, true);
            }
            this.countryPrefill();
        }
    }

    static getFormeoTicketSlugByAttendeesSlideIndex(index) {
        let currentAttendeeSlide = $('#attndeSldr > .slick-item:eq(' + index + ')');
        let formeo_ticket_slug = currentAttendeeSlide.find(".js_ticket_name").attr("formeo_ticket_slug");
        return formeo_ticket_slug;
    }

    static setAttendeeAndTicketHeading(index) {
        let currentAttendeeSlide = $('#attndeSldr > .slick-item:eq(' + index + ')');
        let attendee_counter_label = currentAttendeeSlide.find(".js_attendee_counter_label").text();
        let ticket_name = currentAttendeeSlide.find(".js_ticket_name").text();
        let heading = attendee_counter_label + ":" + ticket_name;
        $(".js_attendee_and_ticket_heading").html(heading);
    }

    static prefillAdditionalContact(fieldLabel, fieldValue, attendee_index) {
        if (fieldValue) {
            if (fieldLabel === 'Title') {
                $('#attendeeTitle_' + attendee_index).val(fieldValue).selectpicker('refresh');
            }
            else if (fieldLabel === 'First Name') {
                $("#attendee_first_name_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Middle Name') {
                $("#attendee_middle_name_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Last Name') {
                $("#attendee_last_name_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Email Address') {
                $("#attendee_email_address_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Date of Birth') {
                $("#attendee_dob_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Phone') {
                $("#attendee_phone_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Address') {
                $("#attendee_address_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Address Line 1') {
                $("#attendee_address_line1_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Address Line 2') {
                $("#attendee_address_line2_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Country') {

            }
            else if (fieldLabel === 'State') {

            }
            else if (fieldLabel === 'City') {

            }
            else if (fieldLabel === 'Post Code') {

            }
            else if (fieldLabel === 'Identification Number') {
                $("#identification_no_" + attendee_index).val(fieldValue);
            }
            else if (fieldLabel === 'Nationality') {
                let prefilled_nationality = fieldValue;
                if (prefilled_nationality) {
                    prefilled_nationality = prefilled_nationality.trim();
                    let country_code = this.getKeyByValue(countries, prefilled_nationality);
                    if (country_code) {
                        $('#attendee_nationality_' + attendee_index).val(country_code).selectpicker('refresh');
                    }
                }
            }
        }
    }

    static prefillAttendeeBuilderFields(fieldName, fieldValue, renderer_selector, isUpdateAditionalInformation = false) {
        // let $labels = $("#attendee_detail_form_render_wrapper").find(".f-field-group > label");
        let $labels = $(renderer_selector).find(".f-field-group > label");
        for (let i = 0; i < $labels.length; i++) {
            let $label = $($labels[i]);
            let label = $label.text();
            label = label ? label.trim() : label;
            if (label) {
                label = label.replace('*', '');
            }
           if (fieldName === label) {
                let $input = $label.parent().find("input, textarea, select");
                if ($input && $input.length > 0) {
                  if (['checkbox', 'radio'].includes($input.attr("type"))) {
                      $input.each(function () {
                          var each_item = $(this);
                          var each_value = each_item.val();
                          each_value = each_value ? each_value.trim() : each_value;
                          if (each_value === fieldValue) {
                              each_item.prop('checked', true);
                          }
                      });

                      if (isUpdateAditionalInformation) {
                          if ($input.attr("type") === "checkbox") {
                              let multiple_value_arr = fieldValue.split(", ");

                              if (multiple_value_arr.length) {
                                  multiple_value_arr.forEach(function (fValue) {
                                      $input.each(function () {
                                          var each_item = $(this);
                                          var each_value = each_item.val();
                                          each_value = each_value ? each_value.trim() : each_value;
                                          if (each_value === fValue) {
                                              each_item.prop('checked', true);
                                          }
                                      });
                                  })
                              }
                          }
                      }
                  } else if (['file'].includes($input.attr("type"))) {

                      if (isUpdateAditionalInformation) {
                          if (!$input.parents(".f-field-group").find(".file_url").length) {
                              $input.parents(".f-field-group").append(fieldValue);
                          }
                      }
                  }
                  else {
                      $input.val(fieldValue);
                  }
                }
           }
        }
    }

    static prefillAttendeeData(renderer_selector) {
        if (attendee_prefilled_data) {
            let attendee_index = renderer_selector.replace("#editor-form_", "")
            for (let [fieldName, fieldValue] of Object.entries(attendee_prefilled_data)) {
                fieldName = fieldName ? fieldName.trim() : fieldName;
                fieldValue = fieldValue ? fieldValue.trim() : fieldValue;
                this.prefillAdditionalContact(fieldName, fieldValue, attendee_index);
                this.prefillAttendeeBuilderFields(fieldName, fieldValue, renderer_selector);
            }
            this.countryPrefill();
        }
    }



    static prefillUpdateAditionalInformationBookingData() {
        if (booking_attendee_prefilled_data) {
            for (let [fieldName, fieldValue] of Object.entries(booking_attendee_prefilled_data)) {
                fieldName = fieldName ? fieldName.trim() : fieldName;
                fieldValue = fieldValue ? fieldValue.trim() : fieldValue;
                this.prefillAttendeeBuilderFields(fieldName, fieldValue, "#buyer_editor_form", true);
            }
        }
    }

    static countryPrefill() {
        let prefilled_country = attendee_prefilled_data["Country"];
        if (prefilled_country) {
            prefilled_country = prefilled_country.trim();
            let country_code = this.getKeyByValue(countries, prefilled_country);
            if (country_code) {
                $('#attendee_country').val(country_code).selectpicker('refresh');
            }
        }
        setTimeout(function () {
            $('#attendee_country').trigger("change");
        }, 100);
    }

    static getKeyByValue(object, value) {
      return Object.keys(object).find(key => object[key] === value);
    }

    static afterAttendeeRenderAction() {
        this.appendAttendeeAnswersHiddenField($("#attendee_detail_form_render_wrapper"));
        setTimeout(function () {
            $("#attendee_detail_form_render_wrapper input[type='checkbox']").each(function () {
                var _self = $(this);
                var field_name = _self.attr('name');
                var last_character = field_name.charAt(field_name.length - 1);
                if (last_character !== ']') {
                    _self.attr("name", _self.attr('name') + "[]");
                }
            });
        }, 100);

        $("#attendeeInfo_form input[type='file']").change(function () {
            let $file_input = $(this);
            $file_input.parent().find("label.error").hide();
            $file_input.removeClass("error");
        });
    }

    static minMaxNumberOfChoiceValidation() {
        $.validator.addMethod("min_max_choice_validation", function(value, element, params) {
            var $field_group = $(element).closest('.f-field-group');
            var min_number_of_choices = $field_group.attr("min_number_of_choices");
            var max_number_of_choices = $field_group.attr("max_number_of_choices");
            var checked_length = $field_group.find('input[type="checkbox"]:checked').length;
            if (min_number_of_choices <= checked_length && checked_length <= max_number_of_choices) {
                return true
            }
            $.validator.messages.min_max_choice_validation = `Please choose  at least ${min_number_of_choices} and at most ${max_number_of_choices} options`;
            return false
        }, $.validator.messages.min_max_choice_validation);
        $.validator.addClassRules({
            min_max_choice_validation: {
                min_max_choice_validation : true
            }
        });
    }

    static validateFormeoPhoneNumber() {
        $.validator.addMethod("formeo_phone_number", function(value, element, params) {
            if (!value) {
                return true;
            }
            const regex = /^[0-9\-+\(\)\s]+$/;
            if (regex.test(value)) {
               return true;
            }
            $.validator.messages.formeo_phone_number = `Invalid phone number`;
            return false
        }, $.validator.messages.formeo_phone_number);
        $.validator.addClassRules({
            formeo_phone_number: {
                formeo_phone_number : true
            }
        });
    }

    static isAttendeeStateRequired() {
        return $("#isAttendeeStateRequired").val() == 1 ? 1 : '';
    }

    static isAttendeeCityRequired() {
        return $("#isAttendeeCityRequired").val() == 1 ? 1 : '';
    }

    static isAttendeePostCodeRequired() {
        return $("#isAttendeePostcodeRequired").val() == 1 ? 1 : '';
    }

    static internationalizeAttendeePhone() {
        if ($('#phoneEnabled').val() == '1') {
            $(".js_attendee_phone").each(function () {
                intlTelInput(this, {
                    nationalMode: false,
                    preferredCountries: ["us", "au"],
                    autoHideDialCode: false,
                    separateDialCode: true,
                    initialCountry: "au",
                });
            });
        }
    }

    static attendeeAddressAutoComplete() {
        let _this = this;
        document.querySelectorAll(".js_attendee_address").forEach(function (input) {
           let attendee_wrapper = $(input).parents(".js_attendee_body_wrapper");
            const searchBox = new google.maps.places.SearchBox(input);
            searchBox.addListener("places_changed", () => {
                var places = searchBox.getPlaces();
                autofillAddresses(places, attendee_wrapper)
            });
        });

        function autofillAddresses(place, attendee_body_wrapper) {
            let attendee_index = $(attendee_body_wrapper).attr('attendee_index');
            let address1 = "";
            let postcode = "";
            let country = "";
            let state = "";
            let city = "";

            if (place[0]) {
                for (const component of place[0].address_components) {

                    // const componentType = component.types[0];

                    // switch (componentType) {
                    //     case "street_number": {
                    //         address1 = `${component.long_name} ${address1}`;
                    //         break;
                    //     }

                    //     case "route": {
                    //         address1 += component.short_name;
                    //         break;
                    //     }
                    //     case "locality":
                    //         city = component.long_name;
                    //         break;

                    //     case "postal_code": {
                    //         postcode = `${component.long_name}${postcode}`;
                    //         break;
                    //     }

                    //     case "postal_code_suffix": {
                    //         postcode = `${postcode}-${component.long_name}`;
                    //         break;
                    //     }

                    //     case "administrative_area_level_1": {
                    //         state = component.long_name;
                    //         break;
                    //     }
                    //     case "country":
                    //         country = component.short_name;
                    //         break;
                    // }

                    const componentTypes = component.types;

                    if(componentTypes.includes('street_number')){
                        address1 = `${component.long_name} ${address1}`;
                    }
                    if(componentTypes.includes('route')){
                        address1 += component.short_name;
                    }
                    if(componentTypes.includes('locality')){
                        city = component.long_name;
                    }
                    if(componentTypes.includes('postal_code')){
                        postcode = `${component.long_name}${postcode}`;
                    }
                    if(componentTypes.includes('postal_code_suffix')){
                        postcode = `${postcode}-${component.long_name}`;
                    }
                    if(componentTypes.includes('administrative_area_level_1')){
                        state = component.long_name;
                    }
                    if(componentTypes.includes('country')){
                        country = component.long_name;
                    }
                }

                let state_required = _this.isAttendeeStateRequired() == 1 ? 'required' : '';
                let city_required = _this.isAttendeeCityRequired() == 1 ? 'required' : '';
                let postcode_required = _this.isAttendeePostCodeRequired() == 1 ? 'required' : '';


                if (country.toLowerCase().indexOf("myanmar") > -1) {
                    country = 'Myanmar';
                }

                if (country == "Czechia") {
                    country = 'Czech Republic';
                }

                $('#attendee_country_' + attendee_index).val(country);
                $('#select2-attendee_country_'+attendee_index+'-container').html(country);  
                $('#attendee_country_' + attendee_index).trigger('select2:select');

                let stateDom = document.getElementById('attendee_state_' + attendee_index);
                if(stateDom){
                    var ddStateOption = stateDom.options;
                    if (ddStateOption) {
                        var isStateExist = true;//checkIfExistsInOptions(ddStateOption, state);
                        if (!isStateExist) {
                            var stateInput = '<input type="text" id="attendee_state_' + attendee_index + '" name="attendee_state[' + attendee_index + ']" class="form-control color-black" value=' +state+ ' maxlength="255">';
                            $("#attendee_state_" + attendee_index).replaceWith(stateInput);
                            $("#attendee_state_" + attendee_index).siblings('span').remove();
                        }
                        else {
                            stateDom.value  = state;
                            $("#attendee_state_" + attendee_index).trigger("change");
                        }
                    }
                    else {
                        stateDom.value  = state;
                    }
                }

                let cityDom = document.getElementById('attendee_city_' + attendee_index);
                if (city && cityDom) {
                    var ddCityOption =  cityDom.options;
                    if (ddCityOption) {
                        var isCityExist = true; //checkIfExistsInOptions(ddCityOption, city);

                        if (!isCityExist) {
                            var cityInput = '<input type="text" id="attendee_city_' + attendee_index + '" name="attendee_city[' + attendee_index + ']" class="form-control color-black" value=' +city+ ' maxlength="255">';
                            $("#attendee_city_" + attendee_index).replaceWith(cityInput);
                            $("#attendee_city_" + attendee_index).siblings('span').remove();
                        }
                        else {
                            cityDom.value  = city;
                            // document.getElementById('select2-city-container').innerHTML  = city;
                            $("#attendee_city_" + attendee_index).trigger("change");
                        }
                    }
                    else {
                        cityDom.value  = city;
                    }
                }
                else {
                    let cityInput = '<input type="text" id="attendee_city_' + attendee_index + '" name="attendee_city[' + attendee_index + ']" class="form-control attendee_city"  maxlength="255" ' + city_required + '>'
                    attendee_body_wrapper.find('.js_attendee_city_dropdown_container').html(cityInput).removeClass("select select-country-mapper-arrow").closest('.form-group').removeClass('error');
                }

                let postCodeDom = document.getElementById('attendee_post_code_' + attendee_index);
                if (postcode && postCodeDom) {

                    var ddOption =  postCodeDom.options;
                    if (ddOption) {

                        var isExist = true; //checkIfExistsInOptions(ddOption, postcode)

                        if (!isExist) {
                            var postcodeInput = '<input type="text" id="attendee_post_code_' + attendee_index + '" name="attendee_post_code[' + attendee_index + ']" class="form-control color-black" value=' +postcode+ ' maxlength="255">';
                            $("#attendee_post_code_" + attendee_index).replaceWith(postcodeInput);
                            $("#attendee_post_code_" + attendee_index).siblings('span').remove();
                        }
                        else {
                            postCodeDom.value  = postcode;
                        }
                    }
                    else {
                        postCodeDom.value  = postcode;
                    }
                }
                else {
                    let postcodeInput = '<input type="text" id="attendee_post_code_' + attendee_index + '" name="attendee_post_code[' + attendee_index + ']" class="form-control attendee_post_code" maxlength="255" ' + postcode_required + '>'
                    attendee_body_wrapper.find('.js_attendee_post_code_dropdown_container').html(postcodeInput).removeClass("select select-country-mapper-arrow").closest('.form-group').removeClass('error');
                }

                $('#attendee_address_line1_' + attendee_index).val(address1);
                $('#attendee_address_line1_' + attendee_index).trigger("change");
                // $('#attendee_country_' + attendee_index).val(country).selectpicker('refresh');
            }
        }
    }

    static attendeeTabAnimation() {
        let _this = this;
        let $attendee_tab_selector = $('.checkout-attendee-tab');
        $attendee_tab_selector.find("a").on("click", function (e) {
            e.preventDefault();
            let _self = $(this);
            let previous_attendee_target = $attendee_tab_selector.find('li.active').find('a').attr('attendee_target');
            $attendee_tab_selector.find('li').removeClass('active');
            _self.parent().addClass('active');
            let attendee_target = _self.attr('attendee_target');

            let tab_height = $(".checkout-attendee-tab").height();
            let header_height = $(".main-header-wrap").height();
            let height_subtract = tab_height + header_height + 60;
            if (previous_attendee_target == '.js_attendee_1') {
                height_subtract = height_subtract + 140;
            }
            let scroll_top = $(attendee_target).offset().top - height_subtract;
            _this.customScrollTo(scroll_top, 0);
        });

        if ($attendee_tab_selector.length) {
            $attendee_tab_selector.width($(".attendee_wrapper").width());

            let attendee_tab_top = $attendee_tab_selector.offset().top;
            jQuery(window).scroll(function ($) {
                let currenTop = jQuery(window).scrollTop();
                if (currenTop > attendee_tab_top) {
                    $attendee_tab_selector.addClass("fixed_attendee");
                }
                else {
                    $attendee_tab_selector.removeClass("fixed_attendee");
                }
            });
        }
    }

    static customScrollTo(topValue, time){
        jQuery("html, body").animate({
            scrollTop: topValue
        }, time);
    }

    static manipulateBuyerBuilderField() {
        $("#buyer_editor_form_render_wrapper").find( "textarea, select, input").each(function () {
            var field_selector = $(this);

            let input_type = field_selector.attr('type');
            // for design purpose
            if (['number', 'file'].includes(input_type)) {
                let wrap_class = '';
                switch (input_type) {
                    case 'number':
                    wrap_class = 'attendee-number-field-wrap';
                    break;
                    case 'file':
                    wrap_class = 'attendee-file-field-wrap';
                    break;
                }
                field_selector.parent().addClass(wrap_class);
            }

            if (field_selector.attr('type') === 'checkbox') {
                field_selector.attr("name", field_selector.attr('name') + "[]");
            }
        });
    }

    static attendeeFormeoFormRequiredActionsAfterFormRender()  {
        this.appendAttendeeAnswersHiddenField($("#buyer_editor_form_render_wrapper"));
        this.manipulateBuyerBuilderField();
        this.minMaxNumberOfChoiceValidation();
        this.internationalizeAttendeePhone();

        let addressEnabled = $('#addressEnabled').val();
        if (addressEnabled == "1") {
            this.attendeeAddressAutoComplete();
        }
        this.attendeeTabAnimation();

        // jQuery UI date picker
        $( ".date_of_birth").datepicker({
            dateFormat: 'dd/mm/yy',
            maxDate: new Date(),
            changeMonth: true,
            changeYear: true,
            yearRange: "-1000:+1000",
        });
    }

    // document.addEventListener("DOMContentLoaded", function(event) {
    //     attendeeFormeoFormRequiredActionsAfterFormRender()
    // });

    static jsOrderSummaryToggle($this) {
        $($this).toggleClass("up-down");
        $(".js_order_summary").toggleClass("order_summary_show");
    }

    static appendFormeoAttendeePhoneFieldsValue=(formData)=> {
        for (let [fieldName, value] of formData) {
            if (/attendee_phone\[[0-9]+\]/.test(fieldName)) {
                let iti = intlTelInput.getInstance(document.querySelector("input[name='" + fieldName + "']"));
                let only_input_value = iti.telInput.value;
                if (only_input_value) {
                    let phone_number = '+'+iti.getSelectedCountryData()?.dialCode+only_input_value;
                    console.log({phone_number});
                    formData.set(fieldName, phone_number);
                }
            }
        }
    
        return formData;
    }

    static showHideAutoFillFromPreviousAttendeeCheckbox() {
        let is_show_autofill_from_booking_checkbox = false;
        let formeo_3_fields = $('#editor-form_0 .formeo_first_name, #editor-form_0 .formeo_last_name, #editor-form_0 .formeo_email_address');
        let contact_3_fields = $('#contact-attendee-form-0 #attendee_first_name_0,#contact-attendee-form-0 #attendee_last_name_0,#contact-attendee-form-0 #attendee_email_address_0');
        if ((formeo_3_fields && formeo_3_fields.length) || (contact_3_fields && contact_3_fields.length)) {
            is_show_autofill_from_booking_checkbox = true;
        }
        if (!is_show_autofill_from_booking_checkbox) {
            $('#js_attendee_autofill_wrapper_0').hide();
        }

        function attendeeFieldsLabel(attendee_index) {
            const attendee_form = $('#editor-form_' + attendee_index);
            const attendee_field_labels = [];
            if (attendee_form && attendee_form.length) {
                attendee_form.find(".f-field-group label").each(function (i, labelEl) {
                    let label = $(labelEl).text();
                    if (label) {
                        label = label.trim();
                    }
                    attendee_field_labels.push(label);
                });
            }

            const contact_form = $('#contact-attendee-form-' + attendee_index);
            if (contact_form && contact_form.length) {
                contact_form.find('input[name^="attendee_"]').each(function (i, ele) {
                    let label = $(ele).prev().text();
                    if (label) {
                        label = label.trim();
                    }
                    attendee_field_labels.push(label);
                })
            }
            return attendee_field_labels;
        }

        $('.js_attendee_body_wrapper').each(function (index, each_attendee_wrapper) {
            const current_attendee_index = $(each_attendee_wrapper).attr('attendee_index');
            if (current_attendee_index > 0) {
                const previous_attendee_index = current_attendee_index - 1;
                const previous_attendee_field_labels = attendeeFieldsLabel(previous_attendee_index)
                const current_attendee_field_labels = attendeeFieldsLabel(current_attendee_index)
                const common_field_labels = current_attendee_field_labels.filter(value => previous_attendee_field_labels.includes(value));
                if (!common_field_labels || common_field_labels.length === 0) {
                    $('#js_attendee_autofill_wrapper_' + current_attendee_index).hide();
                }
            }
        })
    }

    // document.addEventListener("DOMContentLoaded", function(event) {
    //     showHideAutoFillFromPreviousAttendeeCheckbox();
    // });

    static jsAttendeePopulateFromCheckout(_this) {
        if ($(_this).prop('checked')) {
            const first_name = $('#firstName').val();
            const last_name = $('#last-name').val();
            const email = $('#email').val();

            const attendee_1_form = $('#editor-form_0');
            attendee_1_form.find('.formeo_first_name').val(first_name);
            attendee_1_form.find('.formeo_last_name').val(last_name);
            attendee_1_form.find('.formeo_email_address').val(email);

            const attendee_1_contact_form = $('#contact-attendee-form-0');
            attendee_1_contact_form.find('#attendee_first_name_0').val(first_name);
            attendee_1_contact_form.find('#attendee_last_name_0').val(last_name);
            attendee_1_contact_form.find('#attendee_email_address_0').val(email);
        }
    }

    static jsAttendeePopulateFromAttendee(_this) {
        const current_attendee_index = $(_this).closest('.js_attendee_body_wrapper').attr('attendee_index');
        const previous_attendee_index = current_attendee_index - 1;
        const fillForm = $('#editor-form_' + current_attendee_index);
        const getForm = $('#editor-form_' + previous_attendee_index);

        if ($(_this).prop('checked')) {
            this.copyFormValues(getForm, fillForm, current_attendee_index);
            this.copyFormValues($('#contact-attendee-form-' + previous_attendee_index), $('#contact-attendee-form-' + current_attendee_index), current_attendee_index);
        }
    }

    static copyFormValues(source_form, target_form, current_attendee_index) {
        try {
            source_form.find(':input').each(function() {
                const source_input = $(this);
                const inputType = source_input.attr('type');
                const source_input_name = source_input.attr('name');
                const source_input_value = source_input.val();
                if (source_input_name === undefined){
                    return;
                }

                const target_input_name = source_input_name.replace(/\[\d+\]/, '[' + current_attendee_index + ']');

                if (inputType === 'checkbox') {
                    target_form.find('input[name="' + target_input_name + '"][value="' + source_input_value + '"]').prop('checked', source_input.prop('checked'));
                }
                else if (inputType === 'file') {
                    // File inputs cannot be set programmatically for security reasons
                    // can't pre-fill file input fields.
                    // If you need to copy the file selection, you may need to provide the user with another file input.
                }
                else if (inputType === 'radio') {
                    target_form.find('input[type="radio"][name="' + target_input_name + '"][value="' + source_input_value + '"]').prop('checked', source_input.prop('checked'));
                }
                else if (inputType === 'number') {
                    target_form.find('input[name="' + target_input_name + '"]').val(source_input_value);
                }
                else if (source_input.is('select')) {
                    let target_field = target_form.find('select[name="' + target_input_name + '"]');
                    target_field.val(source_input_value);
                    if (target_field.hasClass('countrypicker')) {
                        target_field.selectpicker('refresh').trigger("change");
                    }
                }
                else if (inputType === 'text') {
                    let target_field = target_form.find('input[name="' + target_input_name + '"]');
                    target_field.val(source_input_value);
                }
                else if (source_input.is('textarea')) {
                    target_form.find('textarea[name="' + target_input_name + '"]').val(source_input_value);
                }
                else if (inputType === 'input') {
                    target_form.find('input[name="' + target_input_name + '"]').val(source_input_value);
                }
                else {
                    target_form.find('[name="' + target_input_name + '"]').val(source_input_value);
                }
            });
        }
        catch (e) {
            console.error('copyFormValues error', e)
        }
    }

    static multilineFormeoInstruction(editorJson) {
        let newJson = "";
        try {
            if (editorJson) {
                newJson = JSON.parse(JSON.stringify(editorJson));
                let regex = /(\?<!\\)\n/g;
                for (const [field_id, field_object] of Object.entries(newJson.fields)) {
                    let instruction = newJson.fields[field_id]['attrs']['instruction'];
                    if (instruction) {
                        instruction = instruction.replace(regex, "<br>");
                        newJson.fields[field_id]['attrs']['instruction'] = instruction;
                    }
                }
            }
        }
        catch (e) {
            console.error('Instruction change error', e)
        }
        let  finalJson = newJson ? newJson : editorJson;
        return finalJson;
    }
}

window.EbFormeo = EbFormeo;