define('xwiki-ckeditor-inline', ['jquery', 'xwiki-ckeditor'], function($, ckeditorPromise) {
  var loadCSS = function(url) {
    var link = $('<link>').attr({
      type: 'text/css',
      rel: 'stylesheet',
      href: url
    }).appendTo('head');
  };

  var css = [
    new XWiki.Document('EditSheet', 'CKEditor').getURL('ssx'),
    "../../../webjars/application-ckeditor-webjar/1.48/plugins/xwiki-resource/resourcePicker.min.css",
    "../../../webjars/application-ckeditor-webjar/1.48/plugins/xwiki-macro/macroWizard.min.css",
    "../../../webjars/xwiki-platform-tree-webjar/12.6/tree.min.css",
    "../../../webjars/xwiki-platform-tree-webjar/12.6/finder.min.css"
  ];
  css.forEach(loadCSS);

  $(document).on('xwiki:actions:edit', function(event, data) {
    if (data && data.contentType === 'org.xwiki.rendering.syntax.SyntaxContent' && data.editMode === 'wysiwyg') {
      var container = $(event.target);
      ckeditorPromise.done(function(ckeditor) {
        createEditor(ckeditor, container, data.document, data.deferred, !data.enableSourceMode);
      });
    }
  });

  var createEditor = function(ckeditor, container, xwikiDocument, deferred, disableSourceMode) {
    container.prop('contenteditable', true).attr('data-sourceDocumentSyntax', xwikiDocument.syntax);
    container.each(function() {
      try {
        var editor = ckeditor.inline(this);
        // Disable the source mode if the in-place editor doesn't support it, i.e. XWiki [12.3RC1, 12.4].
        if (disableSourceMode) {
          editor.once('configLoaded', function(event) {
            if (typeof editor.config.removePlugins === 'string') {
              editor.config.removePlugins += ',xwiki-source,xwiki-sourcearea';
            }
          });
        }
        editor.on('instanceReady', function() {
          deferred.resolve(xwikiDocument);
        });
        $(document).on('xwiki:actions:beforeSave.contentEditor', function(event) {
          xwikiDocument[editor.mode === 'source' ? 'content' : 'renderedContent'] = editor.getData();
        });
        $(document).one('xwiki:actions:view', function(event, data) {
          $(document).off('xwiki:actions:beforeSave.contentEditor');
          // Blur the edited content to re-enable the "disabled in inputs" shortcut keys (e.g. the page edit shortcut).
          // We also do this because destroying the editor while the edited content has the focus can lead to an error.
          // See below.
          container.blur().prop('contenteditable', false).removeAttr('contenteditable');
          // We destroy the editor after the edited content has lost the focus completely because the editor has a
          // delayed event listener that tries to access the selection even after the editor has been destroyed.
          setTimeout(function() {
            // Don't update the edited element with the data from the editor because:
            // * the editor data might be wiki syntax if the current mode is Source
            // * the in-place editor updates the edited element anyway using the view HTML (without rendering markers)
            //   and we risk overwriting it.
            editor.destroy(/* noUpdate: */ true);
          }, 0);
        });
      } catch (e) {
        console.log(e);
        new XWiki.widgets.Notification("Failed to initialize CKEditor.", 'error');
        deferred.reject();
      }
    });
  };
});
