wpj.blocek = {
   config: {},
   onReady: function () {
      window.blocekHandler.handleBlocekLoaded();
      window.blocekHandler.handleStartEdit();
   },
   selectImage: function (callback, multi) {
      // open search window
      var win = window.open(this.getUrlPrefix() + 'launch.php?s=search.php&type=photo&postMessage=1&multiSelect=' + (multi ? '1' : '0') + '&inlineEditable=1', 'ImageSelect', 'width=1000,height=780');

      function handleImageFromSearchWindow(event) {
         if (event.data.type !== 'searchPhotos') {
            return;
         }

         callback(event.data.val);
         window.removeEventListener('message', handleImageFromSearchWindow);
      }

      window.addEventListener('message', handleImageFromSearchWindow);

      return false;
   },
   selectVideo: function (callback, multi) {
      // open search window
      var win = window.open(this.getUrlPrefix() + 'launch.php?s=search.php&type=photo&postMessage=1&multiSelect=' + (multi ? '1' : '0') + '&inlineEditable=1', 'VideoSelect', 'width=1000,height=780');

      function handleImageFromSearchWindow(event) {
         if (event.data.type !== 'searchPhotos') {
            return;
         }

         callback(event.data.val);
         window.removeEventListener('message', handleImageFromSearchWindow);
      }

      window.addEventListener('message', handleImageFromSearchWindow);

      return false;
   },
   insertProducts: function (filter, callback) {
      window.wpj.blocekRuntime.insertProducts(filter, callback);
   },
   insertComponent: function (body, callback) {
      window.wpj.blocekRuntime.insertComponent(body, callback);
   },
   initializeAccordionClickAction: () => {
      window.wpj.blocekRuntime.initializeAccordionClickAction();
   },
   initializeSliders: function () {
      window.wpj.blocekRuntime.initializeSliders();
   },
   loadProducts: function () {
      window.wpj.blocekRuntime.loadProducts();
   },
   editImage: function(idImage, callback) {
      // define edit window callback
      window.searchWndCallbacks = {
         blocek_editImage(val, data) {
            callback(val);
         }
      };

      const win = window.open(this.getUrlPrefix() + 'launch.php?s=imageEditor.php&acn=edit&ID=' + idImage + '&callback=blocek_editImage&inlineEditable=1', 'ImageEdit', 'width=1000,height=780');

      return false;
   },
   selectProducts: (() => {
      let handleSelectProducts = undefined;

      return function(filter, callback)  {
         openedWindow = window.open(this.getUrlPrefix() + 'launch.php?s=ProductsFilter.php&acn=add&filter=' +
            encodeURIComponent(filter || '{}') + '&callback=blocek_setProducts&inlineEditable=1', 'ProductsSelect', 'width=1000,height=780');

         if(handleSelectProducts) {
            // Unregister previous listener, so the response is handled only for most recently edited ProductsBlock
            window.removeEventListener('message', handleSelectProducts);
         }

         handleSelectProducts = (event) => {
            if (event.data && event.data?.selectedProducts === 'selectedProducts') {
               try {
                  var obj = JSON.parse(event.data.filter);
                  callback(event.data.filter);
                  window.removeEventListener('message', handleSelectProducts);
               } catch (e) {
                  window.console.log('handleSelectProducts', e, event);
               }
            }
         }

         window.addEventListener('message', handleSelectProducts);

         return false;
      };
   })(),
   selectIcons: (callback) => {
      const win = window.open('/_ckfinder/browse/?type=z_icons', 'IconsSelect', 'width=1000,height=780');

      const timer = setInterval(() => {
         if (win.closed) {
            clearInterval(timer);
            callback();
         }
      }, 100);
   },
   openCKFinder: function(fileInput) {
      CKFinder.popup({
         language: 'cs',
         chooseFiles: true,
         width: 800,
         height: 600,
         onInit: function(finder) {
            finder.on('files:choose', function(evt) {
               var file = evt.data.files.first();
               var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
               nativeInputValueSetter.call(fileInput, file.getUrl());
               var ev = new Event('input', { bubbles: true});
               fileInput.dispatchEvent(ev);
            });
         },
      });
   },
   getUrlPrefix: function() {
      return wpj.blocek.config.urlPrefix;
   },
   getAdminPath: function() {
      return wpj.blocek.config.adminPath;
   },
   isWpjAdmin: function() {
      return wpj.blocek.config.isWpjAdmin;
   },
   allowHtml: function() {
      return wpj.blocek.config.allowHtml;
   },
   getAdminUser: function() {
      return wpj.blocek.config.adminUser;
   },
   startLegacyBlockEdit: function(el) {
      return CKEDITOR.inline(el, {
         customConfig: '/admin/static/js/ckeditor.js?v1',
         toolbar: 'BasicTable',
         filebrowserBrowseUrl: '/_ckfinder/browse/',
         filebrowserImageBrowseUrl: '/_ckfinder/browse/?rsrcType=Obrázky',
         filebrowserUploadUrl: '/ckfinder/connector?command=QuickUpload&type=Soubory',
         filebrowserImageUploadUrl: '/ckfinder/connector?command=QuickUpload&type=Obrázky',
         startupFocus: true,
         toolbar_BasicTable: [
            [
               'Undo',
               'Redo',
               '-',
               'PasteFromWord',
               '-',
               'Bold',
               'Italic',
               '-',
               'NumberedList',
               'BulletedList',
               '-',
               '-',
               'JustifyLeft',
               'JustifyCenter',
               'JustifyRight',
               'JustifyBlock',
               '-',
               'TextColor',
               'RemoveFormat',
               '-',
               'Link',
               'Unlink',
               'Image',
               '-',
               'Table',
               '-',
               'Format',
               '-',
               'Templates',
               'MediaEmbed',
               'Source',
               'ShowBlocks'],
         ],
      });
   },
   getLanguage: function() {
      return wpj.blocek.config.language;
   },
   getFELanguage: function() {
      return wpj.blocek.config.felanguage;
   },
   getComponents: function() {
      return wpj.blocek.config.components ?? [];
   },
   getModules: function() {
      return wpj.blocek.config.modules ?? [];
   },
   getLlmPrompts: function() {
      return wpj.blocek.config?.llmPrompts ?? [];
   }
};
