(function ($, window, Drupal, drupalSettings) {

  $.fn.drupalAjax = (url) => {

    const ajaxSettings = {
      url,
      dialogRenderer: 'off_canvas',
      dialogType: 'dialog',
      dialog: { width: 700 },
    };

    Drupal.ajax(ajaxSettings).execute();

    return;
  };

  $.fn.iframePreviewReload = (storage, id, language) => {
    jQuery('.nodehive-iframe').each(function () {
      this.contentWindow.postMessage('reloadFrame', '*'); // #TODO Ideally, replace '*' with the exact origin of the iframe for better security.
    });
    if (storage === 'node' && id) {
      if (drupalSettings.nodehive_visualeditor.is_multilingual) {
        $.fn.drupalAjax(`/` + language + `/nodehive/node/${id}`);
      } else {
        $.fn.drupalAjax(`/nodehive/node/${id}`);
      }

    }

    return;
  }

  // Flag to check if the listener is already attached.
  let listenerAttached = false;

  Drupal.behaviors.iframeAuthentication = {
    attach: function (context, settings) {
      const iframe = once('iframeAuthentication', '#nodehive-visualeditor', context);
      if (iframe.length > 0) {
        const iframeElement = iframe[0];
        const jwtToken = settings.nodehive_visualeditor.jwt_token;
        const iframeOrigin = settings.nodehive_visualeditor.iframe_origin;

        if (jwtToken && iframeOrigin) {
          iframeElement.onload = function() {
            let authSent = false;

            const sendAuthMessage = () => {
              if (authSent) return; // Prevent duplicate sends
              authSent = true;
              iframeElement.contentWindow.postMessage({
                type: 'nodehive-login',
                token: jwtToken
              }, iframeOrigin);
            };

            // Listen for auth-ready message from iframe
            const handleMessage = (event) => {
              if (event.source === iframeElement.contentWindow &&
                  event.data.type === 'auth-ready' &&
                  event.origin === iframeOrigin) {
                sendAuthMessage();
                window.removeEventListener('message', handleMessage);
              }
            };

            window.addEventListener('message', handleMessage);

            // Fallback timeout in case handshake fails
            setTimeout(() => {
              if (!authSent) {
                sendAuthMessage();
                window.removeEventListener('message', handleMessage);
              }
            }, 3000);
          };
        }
      }
    }
  };

  Drupal.behaviors.iframeListener = {
    attach: function (context, settings) {
      if (!listenerAttached) {
        window.addEventListener('message', function (event) {
          const data = event.data;

          if (data.type === 'paragraph') {
            console.log('Message:', data);
            $('#iframe-current-path').html(data.pathname)
            loadParagraphEditForm(data.id, data.parent_id, data.langcode)
          }

          if (data.type === 'node') {
            console.log('Message:', data);
            $('#iframe-current-path').html(data.pathname)
            loadNodeEditForm(data.id, data.langcode)
          }

          if (data.type === 'fragment') {
            console.log('Message:', data);
            $('#iframe-current-path').html(data.pathname)
            loadFragmentEditForm(data.id, data.langcode)
          }

          if (data.type === 'area') {
            console.log('Message:', data);
            $('#iframe-current-path').html(data.pathname)
            loadAreaEditForm(data.id, data.langcode)
          }

          if (data.type === 'menu') {
            console.log('Message:', data);
            $('#iframe-current-path').html(data.pathname)
            loadMenuEditForm(data.menu_id, data.langcode)
          }

        });

        listenerAttached = true;
      }
    }
  };

  Drupal.behaviors.iframeResize = {
    attach: function (context, settings) {
      const resizeButtons = once('resize-button', '.resize-button', context);
      resizeButtons.forEach(function (button) {
        button.addEventListener('click', function () {
          const width = this.getAttribute('data-size');
          const dataHeight = this.getAttribute('data-height');
          const maxHeight = (window.innerHeight - 200) + 'px';
          var height;
          if (width === '100%') {
            height = (window.innerHeight - 330) + 'px';
          } else if (dataHeight) {
            height = parseInt(dataHeight) > window.innerHeight - 200 ? maxHeight : dataHeight;
          } else {
            height = maxHeight;
          }
          const iframe = document.getElementById('nodehive-visualeditor');
          const browserChrome = document.querySelector('.visualeditor-browser-chrome');

          if (iframe) {
            iframe.style.width = width;
            iframe.style.height = height;
          }

          if (browserChrome) {
            browserChrome.style.maxWidth = (width === '100%') ? '' : width;
          }

          // Toggle active state on buttons.
          document.querySelectorAll('.resize-button').forEach(function (btn) {
            btn.classList.remove('is-active');
          });
          this.classList.add('is-active');
        });
      });
    }
  };

  Drupal.behaviors.dynamicIframeSrc = {
    attach: function (context, settings) {
      const sidebarLinks = once('dynamicIframeSrc', '.visualeditor-content-sidebar #results-wrapper a.open_in_iframe', context);
      sidebarLinks.forEach(function (link) {
        link.addEventListener('click', function (e) {
          e.preventDefault(); // Prevent the default link behavior.
          const newSrc = this.getAttribute('href'); // Get the href attribute of the clicked link.
          const iframe = document.getElementById('nodehive-visualeditor'); // Reference the iframe by ID.
          if (iframe) {
            iframe.src = newSrc; // Set the new src for the iframe.
          }
        });
      });
    }
  };

  Drupal.behaviors.toggleContentBrowser = {
    attach: function (context, settings) {
      // Ensure the event listener is added only once
      const button = once('toggleContentBrowser', '.nodehive-content-browser', context);
      if (button.length > 0) {
        // Check the saved state and apply it
        const sidebar = document.querySelector('.visualeditor-content-sidebar');
        const sidebarState = localStorage.getItem('Nodehive.visual_editor.toggle_content_browser');
        if (sidebarState === 'hidden') {
          sidebar.style.display = 'none';
        } else {
          sidebar.style.display = 'block';
        }

        // Add the event listener to toggle the sidebar visibility
        button[0].addEventListener('click', function (e) {
          e.preventDefault();
          if (sidebar.style.display === 'none') {
            sidebar.style.display = 'block';
            localStorage.setItem('Nodehive.visual_editor.toggle_content_browser', 'visible');
          } else {
            sidebar.style.display = 'none';
            localStorage.setItem('Nodehive.visual_editor.toggle_content_browser', 'hidden');
          }
        });
      }
    }
  };


  Drupal.behaviors.debounceSearch = {
    attach: function (context, settings) {
      let timeout;

      function delay(callback, ms) {
        var timer = 0;
        return function() {
          var context = this, args = arguments;
          clearTimeout(timer);
          timer = setTimeout(function () {
            callback.apply(context, args);
          }, ms || 0);
        };
      }

      const searchInput = $('#edit-search');
      if (searchInput.length) {
        searchInput.keyup(delay(function (e) {
          $('#edit-search').trigger('change');
        }, 200));
      }
    }
  };


  Drupal.behaviors.spaceSelector = {
    attach: function (context, settings) {

      $("#nodehive-spaces-selector").on('change', function () {
        const selectedSpaceUrl = this.value;

        const newUrl = `/space/${selectedSpaceUrl}/visualeditor`;
        window.location.href = newUrl;
      });

    }
  };

  function loadParagraphEditForm(paragraph_id, node_id, langcode = null) {
    if (langcode && drupalSettings.nodehive_visualeditor.is_multilingual) {
      $.fn.drupalAjax(`/` + langcode + `/nodehive/node/` + node_id + `/paragraph/` + paragraph_id);
      return;
    } else {
      $.fn.drupalAjax(`/nodehive/node/` + node_id + `/paragraph/` + paragraph_id);
    }
  }

  function loadNodeEditForm(node_id, langcode = null) {
    if (langcode && drupalSettings.nodehive_visualeditor.is_multilingual) {
      $.fn.drupalAjax(`/` + langcode + `/nodehive/node/` + node_id);
      return;
    } else {
      $.fn.drupalAjax(`/nodehive/node/` + node_id);
    }

  }

  function loadFragmentEditForm(fragment_id, lang = null) {
    $.fn.drupalAjax(`/nodehive/fragment/` + fragment_id);
  }

  function loadAreaEditForm(area_id, lang = null) {
    $.fn.drupalAjax(`/nodehive/area/` + area_id);
  }

  function loadMenuEditForm(menu_id, lang = null) {
    $.fn.drupalAjax(`/nodehive/menu/` + menu_id);
  }

})(jQuery, window, Drupal, drupalSettings);




