/**
 * @file
 * FlowDrop Data Viewer Component JavaScript
 *
 * Provides collapse toggle and copy-to-clipboard functionality.
 */

(function (Drupal, once) {
  "use strict";

  /**
   * Behavior for data viewer component interactions.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.flowdropDataViewer = {
    attach: function (context) {
      // Handle collapse toggle buttons
      const toggleButtons = once(
        "flowdrop-data-viewer-toggle",
        "[data-flowdrop-collapse-toggle]",
        context
      );

      toggleButtons.forEach(function (button) {
        var handler = function () {
          var expanded = button.getAttribute("aria-expanded") === "true";
          var targetId = button.getAttribute("aria-controls");
          var target = document.getElementById(targetId);

          if (target) {
            button.setAttribute("aria-expanded", String(!expanded));
            target.classList.toggle(
              "fd-data-viewer__content--collapsed",
              expanded
            );
            target.classList.toggle(
              "fd-detail-section__content--collapsed",
              expanded
            );
          }
        };
        button.addEventListener("click", handler);
        button._flowdropToggleHandler = handler;
      });

      // Handle copy buttons
      const copyButtons = once(
        "flowdrop-data-viewer-copy",
        "[data-flowdrop-copy-json]",
        context
      );

      copyButtons.forEach(function (button) {
        var handler = function () {
          var viewer = button.closest(".fd-data-viewer");
          var codeElement = viewer
            ? viewer.querySelector("[data-flowdrop-json]")
            : null;

          if (codeElement) {
            var textToCopy = codeElement.textContent;

            navigator.clipboard.writeText(textToCopy).then(
              function () {
                // Show success feedback
                var originalText = button.querySelector("span").textContent;
                button.querySelector("span").textContent = "Copied!";
                button.classList.add("fd-data-viewer__copy-btn--success");

                setTimeout(function () {
                  button.querySelector("span").textContent = originalText;
                  button.classList.remove("fd-data-viewer__copy-btn--success");
                }, 2000);
              },
              function (err) {
                console.error("Failed to copy text: ", err);
              }
            );
          }
        };
        button.addEventListener("click", handler);
        button._flowdropCopyHandler = handler;
      });

      // Pretty print JSON in code blocks
      const codeBlocks = once("flowdrop-data-viewer-json", "[data-flowdrop-json]", context);

      codeBlocks.forEach(function (codeElement) {
        try {
          const rawJson = codeElement.textContent.trim();
          if (rawJson && rawJson !== "{}") {
            const parsed = JSON.parse(rawJson);
            codeElement.textContent = JSON.stringify(parsed, null, 2);
          }
        } catch (e) {
          // If not valid JSON, leave as-is
          console.debug("Data viewer content is not JSON:", e);
        }
      });
    },

    detach: function (context, settings, trigger) {
      if (trigger !== "unload") {
        return;
      }

      var toggleButtons = context.querySelectorAll("[data-flowdrop-collapse-toggle]");
      toggleButtons.forEach(function (button) {
        if (button._flowdropToggleHandler) {
          button.removeEventListener("click", button._flowdropToggleHandler);
          button._flowdropToggleHandler = null;
        }
      });

      var copyButtons = context.querySelectorAll("[data-flowdrop-copy-json]");
      copyButtons.forEach(function (button) {
        if (button._flowdropCopyHandler) {
          button.removeEventListener("click", button._flowdropCopyHandler);
          button._flowdropCopyHandler = null;
        }
      });
    },
  };
})(Drupal, once);
