/**
 * @file
 * FlowDrop Data Viewer Component JavaScript
 *
 * Provides collapse toggle and copy-to-clipboard functionality.
 *
 * @param {object} Drupal The Drupal API namespace.
 * @param {Function} once The "once" deduplication library.
 */

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

      toggleButtons.forEach((button) => {
        const handler = () => {
          const expanded = button.getAttribute('aria-expanded') === 'true';
          const targetId = button.getAttribute('aria-controls');
          const 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((button) => {
        const handler = () => {
          const viewer = button.closest('.fd-data-viewer');
          const codeElement = viewer
            ? viewer.querySelector('[data-flowdrop-json]')
            : null;

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

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

                setTimeout(() => {
                  button.querySelector('span').textContent = originalText;
                  button.classList.remove('fd-data-viewer__copy-btn--success');
                }, 2000);
              },
              () => {
                // Clipboard write failed (permissions, focus, etc.) — leave
                // the button state unchanged so the user can retry.
              },
            );
          }
        };
        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((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.
        }
      });
    },

    detach(context, settings, trigger) {
      if (trigger !== 'unload') {
        return;
      }

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

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