(function ($, Drupal, once) {
  'use strict';

  Drupal.behaviors.spacesIframeAuthentication = {
    attach: function (context, settings) {
      once('spaces-iframe-authentication', '.spaces-iframe', context).forEach(function (iframe) {
        const jwtToken = settings.nodehive_core?.spaces_iframe?.jwt_token;
        const iframeOrigins = settings.nodehive_core?.spaces_iframe?.iframe_origins;
        const tabId = iframe.getAttribute('data-tab-id');
        const iframeOrigin = iframeOrigins?.[tabId];

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

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

            // Listen for auth-ready message from iframe
            const handleMessage = (event) => {
              if (event.source === iframe.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.spacesIframeTabs = {
    attach: function (context, settings) {
      once('spaces-iframe-tabs', '.spaces-iframe-tabs', context).forEach(function (element) {
        const $tabs = $(element);
        const $buttons = $tabs.find('.spaces-iframe-tab-button');
        const $contents = $tabs.find('.spaces-iframe-tab-content');

        const $urlDisplay = $tabs.find('.spaces-iframe-url');

        // Function to switch tabs
        function switchTab($button) {
          const tabId = $button.data('tab');

          // Update button states
          $buttons.attr('aria-selected', 'false');
          $button.attr('aria-selected', 'true');

          // Update content visibility
          $contents.attr('aria-hidden', 'true').hide();
          $('#' + tabId).attr('aria-hidden', 'false').show();

          // Update address bar URL
          const url = $button.attr('data-url');
          if (url && $urlDisplay.length) {
            $urlDisplay.text(url);
          }
        }

        // Add click handlers
        $buttons.on('click', function (e) {
          e.preventDefault();
          switchTab($(this));
        });

        // Set initial state
        const $activeButton = $buttons.filter('[aria-selected="true"]');
        if ($activeButton.length) {
          switchTab($activeButton);
        }
      });
    }
  };
})(jQuery, Drupal, once);
