/**
 * Class for handling radio/checkbox field functionality in Elementor forms.
 */
class RADIO extends elementorModules.frontend.handlers.Base {

    /**
     * Retrieves the default radio/checkbox field functionality.
     * @returns {Object} An object containing selector configurations.
     */
    getDefaultSettings() {
      return {
        selectors: {
          selectElementFront: '.elementor-field-type-radio,.elementor-field-type-checkbox',
          divEditor: '.editor_data_js',
          form: '.elementor-form'
        },
      };
    }
  
    /**
     * Retrieves the default elements based on the settings defined.
     * @returns {Object} An object containing jQuery elements for the radio/checkbox field.
     */
    getDefaultElements() {
      const selectors = this.getSettings('selectors');
      return {
        $selectElement: this.$element.find(selectors.selectElement),
        $divEditor: this.$element.find(selectors.divEditor),
        $form: this.$element.find(selectors.form),
      };
    }
  
  
    /**
     * Binds events to the elements. This method is intended to be overridden by subclasses to add specific event handlers.
     */
    bindEvents() {
      this.fieldIds = [];
      this.controlData = {};
      this.geteditorUserData();
      this.appendCSS();    
      this.triggerChangeEvent(); 
    }

    geteditorUserData() {
      const divEditorElement = this.elements.$divEditor;
      const divEditorObject = jQuery(divEditorElement);
      divEditorObject.each((index, element) => { // use an arrow function
        const $element = jQuery(element);
        const classes = $element.attr('class').split(' ');
        const cfefClasses = classes.filter(cls => cls.startsWith('cfef'));
        let uniqueId;
        const controlData = {};
        cfefClasses.forEach(cls => {
          // const [key, value] = cls.replace('cfef', '').split('_', 2);
          const [key, value] = cls.replace('cfef', '').split(/_(.+)/);
  
          if (key === 'uniqueId') {
            uniqueId = value;
            $element.closest('.elementor-field-group').addClass(`elementor-field-group-${uniqueId}`);
            this.fieldIds.push(uniqueId); // push the fieldId to the array
          } else {
            if (!this.controlData[uniqueId]) {
              this.controlData[uniqueId] = {};
            }
            this.controlData[uniqueId][key] = value;
            
          }
        });
      });
    }
  
    /**
     * Retrieves and stores unique radio/checkbox input IDs from the Elementor textarea element.
     */
    appendCSS() {
      this.fieldIds.forEach(uniqueId => {
        const controlData = this.controlData[uniqueId];
        let fieldtarget;
  
        if (this.$element.find(`.elementor-field-group-${controlData.customId}`).length > 0) {
          fieldtarget = this.$element.find(`.elementor-field-group-${controlData.customId}`);
          fieldtarget.addClass(`elementor-repeater-item-${uniqueId}`);
        } else {
          fieldtarget = this.$element.find(`.elementor-field-group-${uniqueId}`);
          fieldtarget.addClass(`elementor-repeater-item-${uniqueId}`);
        }
     
        const Inputs = fieldtarget.find('input[type="radio"], input[type="checkbox"]');
        const styleClass = controlData.style;
        if (Inputs.length > 0 && styleClass) {
          Inputs.each( (indx,ele) => {
            let nearestLabel = '';
            jQuery(ele).addClass(styleClass);
            if (styleClass == "cfkef-swtch-Input" || styleClass == "switch") {
              fieldtarget.addClass("cfkef-switcher");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-sub-swtch');
              nearestLabel.append(`
                            <span>
                            </span>
                        `);
            }
            if (styleClass == "cfkef-cov-Input") {
              fieldtarget.addClass("cfkef-cover");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-sub-cover');
              nearestLabel.append(`
                              <span>
                              </span>
                            `);
            }
            if (styleClass == "cfkef-chcklist-Input") {
              fieldtarget.addClass("cfkef-checklist");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-sub-checklist');
              nearestLabel.append(`
                            <span>
                            </span>
                          `);
            }
            if (styleClass == "cfkef-sq-Input" || styleClass == "DotSquare") {
              fieldtarget.addClass("cfkef-dotSquare");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-dotsq');
              nearestLabel.append(`
                            <span>
                            </span>
                          `);
            }
            if (styleClass == "cfkef-ci-Input" || styleClass == "DotCircle") {
              fieldtarget.addClass("cfkef-dotCircle");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-dotci');
              nearestLabel.append(`
                            <span>
                            </span>
                          `);
            }
            if (styleClass == "cfkef-sqChk-Input" || styleClass == "style4") {
              fieldtarget.addClass("cfkef-square");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-sub-square');
              nearestLabel.append(`
                              <span>
                                <svg>
                                  <use xlink:href="#check-4"></use>
                                </svg>
                              </span>
                            `);
              fieldtarget.append(`
                              <svg class="inline-svg">
                                <symbol id="check-4" viewbox="0 0 12 10">
                                  <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
                                </symbol>
                              </svg>
                            `);
            }
  
            if (styleClass == "cfkef-cirChk-Input" || styleClass == "round") {
              fieldtarget.addClass("cfkef-round");
              nearestLabel = jQuery(ele).next('label');
              nearestLabel.addClass('cfkef-sub-round');
              nearestLabel.append(`
                              <span>
                                <svg>
                                  <use xlink:href="#check-5"></use>
                                </svg>
                              </span>
                            `);
              fieldtarget.append(`
                              <svg class="inline-svg">
                                <symbol id="check-5" viewbox="0 0 12 10">
                                  <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
                                </symbol>
                              </svg>
                        `);
            }
  
            nearestLabel.click(this.labelPreventDefaultHandler);
          });
        } else {
          console.warn(`No radio Inputs found or styleClass is undefined for .elementor-field-group-${uniqueId}`);
        }
      });
    }
  
      labelPreventDefaultHandler(e){
        e.preventDefault();
        const nearestOption = e.target.closest('.elementor-field-option');
        const nearestInput = nearestOption.querySelector('input');
        const inputType = nearestInput.getAttribute('type');
        nearestInput.checked = !nearestInput.checked;
        const siblings = Array.from(nearestOption.parentNode.children).filter(child => child !== nearestOption);
        siblings.forEach(sibling => {
          if(inputType == 'radio'){
            const siblingInput = sibling.querySelector('input');
            siblingInput.checked = false;    
          }
        });
      }

    triggerChangeEvent(){
      const self = this;
      let body = this.elements.$divEditor.closest('body');
      let form = this.elements.$form
      // Trigger change event on styled radio inputs
      body.off('click');
      body.on('click', '.elementor-field-option label', function(e) {
          e.preventDefault(); // Prevent default label behavior
          const input = jQuery(this).prev('input[type="radio"], input[type="checkbox"]');
          if (input.length) {
                  // Handle radio inputs (exclusive selection within group)
                  if (input.attr('type') === 'radio') {
                    input.prop('checked', true).trigger('change');
                  }

                  // Handle checkbox inputs (toggle state)
                  if (input.attr('type') === 'checkbox') {
                      // input.prop('checked', !input.prop('checked')).trigger('change');
                      if(jQuery('body').hasClass('elementor-editor-active')){
                        // input.prop('checked',!input.prop('checked'))
                      }else{
                        if(window.location.protocol === 'https'){
                          input.prop('checked',!input.prop('checked'))
                        }else{
                          // do nothing
                        }
                      }
                  }

                const customEvent = new CustomEvent('cfkef:styled_rc_change', {
                    detail: {
                        sourceElement: this  
                    }
                });
                form[0].dispatchEvent(customEvent);
          }
      });
    }
}
  
  jQuery(window).on('elementor/frontend/init', () => {
    const addHandler = ($element) => {
      elementorFrontend.elementsHandler.addHandler(RADIO, {
        $element,
      });
    };
  
    elementorFrontend.hooks.addAction('frontend/element_ready/form.default', addHandler);
  });
  
  