/**
 * @file
 * JavaScript behaviors for Tippy.js tooltip integration.
 */

(function ($, Drupal, once) {
  var tooltipDefaultOptions = {
    delay: 100
  };

  // @see https://atomiks.github.io/tippyjs/v6/all-props/
  Drupal.webform = Drupal.webform || {};

  Drupal.webform.tooltipElement = Drupal.webform.tooltipElement || {};
  Drupal.webform.tooltipElement.options = Drupal.webform.tooltipElement.options || tooltipDefaultOptions;

  Drupal.webform.tooltipLink = Drupal.webform.tooltipLink || {};
  Drupal.webform.tooltipLink.options = Drupal.webform.tooltipLink.options || tooltipDefaultOptions;

  /**
   * Initialize tooltip element support.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformTooltipElement = {
    attach(context) {
      if (!window.tippy) {
        return;
      }

      $(once('webform-tooltip-element', '.js-webform-tooltip-element', context)).each(function () {
        // Checkboxes, radios, buttons, toggles, etc… use fieldsets.
        // @see \Drupal\webform\Plugin\WebformElement\OptionsBase::prepare
        var $element = $(this);
        var $description;
        if ($element.is('fieldset')) {
          $description = $element.find('> .fieldset-wrapper > .description > .webform-element-description.visually-hidden, > .fieldset__wrapper > .fieldset__suffix > .description.visually-hidden');
        }
        else {
          $description = $element.find('> .description > .webform-element-description.visually-hidden');
        }

        if (!$description.length) {
          return;
        }

        var options = $.extend({
          content: $description.html(),
          allowHTML: true
        }, Drupal.webform.tooltipElement.options);

        tippy(this, options);
      });
    }
  };

  /**
   * Initialize jQuery UI tooltip link support.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformTooltipLink = {
    attach(context) {
      if (!window.tippy) {
        return;
      }

      $(once('webform-tooltip-link', '.js-webform-tooltip-link', context)).each(function () {
        var title = $(this).attr('title');
        if (title) {
          var options = $.extend({
            content: title,
            allowHTML: true
          }, Drupal.webform.tooltipLink.options);

          tippy(this, options);
        }
      });
    }
  };

})(jQuery, Drupal, once);
