var iconsControl = elementor.modules.controls.BaseData.extend({ 

  onReady: function() {
    // Init variables
    this.control_select = this.$el.find(".icon-select");
    this.save_input = this.$el.find(".icon-save-value");

    // Get icons
    const icons = JSON.parse( rad_data.icons );

    // Init select 2 to enable user search among the icons
    this.control_select.select2({
      data: icons,
      templateResult: ( icon ) => {

        const svg = jQuery( icon.svg )
          .attr("width", "20px")
          .attr("height", "20px")
          .css("margin-right", "15px")
          .prop("outerHTML");
        
        icon = jQuery(`
          <div style="display: flex; align-items: center;">
            ${svg} 
            <span id="${icon.id}">${icon.text}</span>
          </div>`
        );

        return icon;
      }

    });

    // Mark previously saved data as selected
    if ( this.save_input ) {
      this.control_select.val( this.save_input.val() );
      this.control_select.trigger('change'); 
    } 

    // Save the value on change
    this.control_select.on( "change", () => this.saveValue() );
  },

  saveValue: function() {
    this.setValue( this.control_select.val() );
  },

  onBeforeDestroy: function() {
    this.saveValue();
  }

});

elementor.addControlView( "rad-icons-control", iconsControl );