(function ($, Drupal) {

  function init(editor) {
    const TraitManager = editor.TraitManager;
    TraitManager.addType('html', Object.assign({}, TraitManager.defaultTrait, {

      afterInit: function () {
        const el = this.getInputEl();
        const format = drupalSettings.pagedesigner.filter_format;
        let tries = 0;
        const maxTries = 50

        if (Drupal.editors.ckeditor5) {
          Drupal.editors.ckeditor5.attach(el, drupalSettings.editor.formats[format]);

          // Poll until editor instance is ready
          const editorId = el.getAttribute('data-ckeditor5-id');
          const waitForEditor = () => {
            const editorInstance = Drupal.CKEditor5Instances.get(editorId);
            if (editorInstance) {
              editorInstance.model.document.on('change:data', () => {
                this.model.setTargetValue(editorInstance.getData());
              });
            } else if (tries < maxTries) {
              tries++;
              setTimeout(waitForEditor, 20);
            } else {
              console.error('Failed to initialize CKEditor 5 instance.');
            }
          };

          waitForEditor();
        } else {
          console.error('CKEditor 5 is not loaded.');
        }
      },

      getInputEl: function () {
        if (!this.inputEl) {
          var input = document.createElement('textarea');
          // input.innerHTML = this.model.get('value');
          var value = this.target.attributes.attributes[this.model.get('name')];
          if (value) {
            input.innerHTML = value;
          }
          input.id = 'component_' + this.target.get('entityId') + '_' + this.model.get('name');
          // Ckeditor5 use the rows attribute to set the height of the textarea.
          input.setAttribute('rows', 10);
          this.inputEl = input;
        }
        return this.inputEl;
      },
      getRenderValue: function (value) {
        if (typeof this.model.get('value') == 'undefined') {
          return value;
        }
        return this.model.get('value');
      }
    }));
  }

  Drupal.behaviors.pagedesigner_trait_html = {
    attach: function (context, settings) {
      $(document).on('pagedesigner-init-traits', function (e, editor) {
        init(editor);
      });
    }
  };

})(jQuery, Drupal);
