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

  Drupal.behaviors.nodehivePreviewTabs = {
    attach: function (context, settings) {
      once('nodehive-preview-tabs', '.nodehive-preview-tabs', context).forEach(function (element) {
        const tabButtons = element.querySelectorAll(".nodehive-preview-tab-button");
        const tabContents = element.querySelectorAll(".nodehive-preview-tab-content");

        function showTab(spaceId) {
          // Reset all tabs
          tabButtons.forEach(btn => {
            btn.classList.remove('is-active');
          });
          tabContents.forEach(content => {
            content.classList.remove('is-active');
          });

          // Activate selected tab
          const selectedButton = element.querySelector(`.nodehive-preview-tab-button[data-space-id="${spaceId}"]`);
          const selectedContent = element.querySelector(`.nodehive-preview-tab-content[data-space-id="${spaceId}"]`);

          if (selectedButton && selectedContent) {
            selectedButton.classList.add('is-active');
            selectedContent.classList.add('is-active');

            // Only refresh iframe for space preview tabs, not for structure tab
            if (spaceId !== 'structure') {
              const iframe = selectedContent.querySelector("iframe");
              if (iframe) {
                iframe.src = iframe.src;
              }
            }
          }
        }

        // Show structure tab by default
        showTab('structure');

        // Add click handlers to all tab buttons
        tabButtons.forEach(button => {
          button.addEventListener("click", function() {
            const spaceId = this.getAttribute("data-space-id");
            showTab(spaceId);
          });
        });

        // Handle iframe loading states
        const iframes = element.querySelectorAll(".nodehive-preview-iframe");
        iframes.forEach(iframe => {
          iframe.style.opacity = "0";
          iframe.addEventListener("load", function() {
            this.style.opacity = "1";
          });
        });
      });
    }
  };
})(jQuery, Drupal);
