/**
 * @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(
        "fd-data-viewer-toggle",
        "[data-fd-collapse-toggle]",
        context
      );

      toggleButtons.forEach(function (button) {
        button.addEventListener("click", function () {
          const expanded = this.getAttribute("aria-expanded") === "true";
          const targetId = this.getAttribute("aria-controls");
          const target = document.getElementById(targetId);

          if (target) {
            this.setAttribute("aria-expanded", String(!expanded));
            target.classList.toggle(
              "fd-data-viewer__content--collapsed",
              expanded
            );
            target.classList.toggle(
              "fd-detail-section__content--collapsed",
              expanded
            );
          }
        });
      });

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

      copyButtons.forEach(function (button) {
        button.addEventListener("click", function () {
          const viewer = this.closest(".fd-data-viewer");
          const codeElement = viewer
            ? viewer.querySelector("[data-fd-json]")
            : null;

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

            navigator.clipboard.writeText(textToCopy).then(
              function () {
                // Show success feedback
                const 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);
              }
            );
          }
        });
      });

      // Pretty print JSON in code blocks
      const codeBlocks = once("fd-data-viewer-json", "[data-fd-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);
        }
      });
    },
  };
})(Drupal, once);
