function generateUniqueId() {
  const timestamp = new Date().getTime();
  const randomPart = Math.random().toString(36).substr(2, 9); // Gera parte aleatória de tamanho 9

  return `${timestamp}-${randomPart}`;
}

const editorConfig = {
  tinymce: {
    wpautop: true,
    plugins: 'charmap colorpicker hr lists paste tabfocus textcolor fullscreen wordpress wpautoresize wpeditimage wpemoji wpgallery wplink wptextpattern',
    toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,wp_more,spellchecker,fullscreen,wp_adv,listbuttons',
    toolbar2: 'styleselect,strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help,image', // Adicionando 'image' à barra de ferramentas
    textarea_rows: 20,
    height: 300,
  },
  quicktags: { buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close' },
  mediaButtons: false,
};

jQuery(function ($) {

  $('.o2-editor').each(function () {
    let editorWrap = $(this);
    let editorID = editorWrap.attr('id');
    let mediaButtons = editorWrap.data('media-buttons') == 1;

    if (editorID) {
      wp.editor.initialize(editorID, { ...editorConfig, mediaButtons });
    }
  });

  const handlerUpdate = (wrap) => {
    $('.o2-editor', wrap).each(function () {
      let editorWrap = $(this);
      let editorID = editorWrap.attr('id');
      let mediaButtons = editorWrap.data('media-buttons') == true;

      if (editorID) {
        wp.editor.remove(editorID);
        wp.editor.initialize(editorID, { ...editorConfig, mediaButtons });
      }
    });
  }

  const handleAdd = (wrap) => {
    $('.o2-editor', wrap).each(function () {
      let editorWrap = $(this);
      const uniqueId = generateUniqueId();
      let mediaButtons = editorWrap.data('media-buttons') == 1;

      editorWrap.attr('id', uniqueId);
      wp.editor.remove(uniqueId);
      wp.editor.initialize(uniqueId, { ...editorConfig, mediaButtons });
    });
  }


  $(document).on('RepeatUpdate', ({ detail }) => handlerUpdate(detail.repeat)).on('RepeatAdd', ({ detail }) => handleAdd(detail.el));

});
